sunytest
sunytest

Reputation: 15

dataframe with date as index, fill other dates with previous items

I have a dataframe in python with dates as index but the dates skip weekends and holidays. What's the cleanest way to add back the missing date and fill the columns with the previous rows.

For example, 18/3/2017 will have all the same figures as 17/3/2017 while 19/3/2017 will have the same figures as 18/3/2017

    Index       col1     col2      col3     col4

17/3/2017   17975694  4527000  16867630  3640000

20/3/2017   18199194  4670000  17403630  3638000

21/3/2017   17996694  4770500  17656630  3652000

Upvotes: 0

Views: 47

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

You could use resample with ffill:

df.resample('D').ffill()

Output:

                col1     col2      col3     col4
Index                                           
2017-03-17  17975694  4527000  16867630  3640000
2017-03-18  17975694  4527000  16867630  3640000
2017-03-19  17975694  4527000  16867630  3640000
2017-03-20  18199194  4670000  17403630  3638000
2017-03-21  17996694  4770500  17656630  3652000

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249093

Use reindex(method='ffill'):

df.reindex(pd.date_range('2017-03-15', '2017-03-25'), method='ffill')

Upvotes: 0

Related Questions