How to align indexes of many dataframes and fill in respective missing values in Pandas?

非 Y 不嫁゛ 提交于 2019-12-05 21:15:42
michael_j_ward

Is this the behavior you are trying to achieve? Note that this method works regardless of whether or not the indexes on the dataframes are monotonic.

df1 = pd.DataFrame({'values': 1}, index=pd.DatetimeIndex(['2016-06-01', '2016-06-03']))
df2 = pd.DataFrame({'values': 2}, index=pd.DatetimeIndex(['2016-06-02', '2016-06-04', '2016-06-07']))
df3 = pd.DataFrame({'values': 3}, index=pd.DatetimeIndex(['2016-06-01', '2016-06-05']))

df = pd.concat([df1,df2,df3], axis=1).ffill().bfill()
df.columns = ['values1', 'values2', 'values3']
df

Which gives:

          values1  values2  values3
2016-05-04  1.0     2.0     3.0
2016-06-01  1.0     2.0     3.0
2016-06-02  1.0     2.0     3.0
2016-06-03  1.0     2.0     3.0
2016-06-05  1.0     2.0     3.0

Or if you just want the data-frames left separate, this will also work regardless of whether the data-frame has a monotonic index.

commonIndex = df1.index | df2.index | df3.index
df2.reindex(commonIndex).ffill()

EDIT:

I had a snippet here that reproduced your error, but I think it works better as its own question- so take a look here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!