Insert missing weekdays in pandas dataframe and fill them with NaN

邮差的信 提交于 2019-12-06 16:02:16

You can use reindex:

df.index = pd.to_datetime(df.index)

df.reindex(pd.date_range('2016-09-30', '2016-10-05', freq=BDay()))
Out: 
            price     vol
2016-09-30   10.0  2020.0
2016-10-03   20.0  2424.0
2016-10-04    NaN     NaN
2016-10-05    5.0   232.0

Alternatively, you can use pandas.DataFrame.resample(), specifying 'B' for Business Day with no need to specify beginning or end date sequence as along as the dataframe maintains a datetime index

df = df.resample('B').sum()

#             price     vol
# date                     
# 2016-09-30   10.0  2020.0
# 2016-10-03   20.0  2424.0
# 2016-10-04    NaN     NaN
# 2016-10-05    5.0   232.0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!