首页 > 解决方案 > pd.concat() 未在同一索引上合并

问题描述

我有一个包含预测的 DataFrame fcst,它看起来像这样:

             yhat        yhat_lower  yhat_upper
ds          
2015-08-31  -0.443522   -19.067399  17.801234
2015-09-30  6.794625    -31.472186  46.667981
...

进行此转换后:

fcst2 = fcst["yhat"].to_frame().rename(columns={"yhat":"test1"})
fcst3 = fcst["yhat"].to_frame().rename(columns={"yhat":"test2"})

我想在日期索引上将它们连接起来:

pd.concat([fcst2,fcst3])

但我收到一个未在索引上对齐的 DataFrame:

             test1     test2
ds      
2015-08-31  -0.443522   NaN
2015-09-30  6.794625    NaN
... ... ...
2017-05-31  NaN 95.563262
2017-06-30  NaN 85.829916

尽管这样:

(fcst2.index == fcst3.index).any()

返回真。

我的问题是:为什么两个 DataFrame 没有在索引上连接,我该怎么做才能解决这个问题?

我知道 join 函数,但是由于我计划添加的其他一些 DataFrame 中缺少某些日期,我相信该concat函数可能会更好。

标签: pythonpython-3.xpandasdataframe

解决方案


调用concat设置axis1

pd.concat([df1, df2], axis=1)

推荐阅读