pd.concat() 不合并在同一索引上



我有一个包含名为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])

但是我收到一个在索引上未对齐的数据帧:

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()

返回 True。

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

我知道联接函数,但由于我计划添加的其他一些数据帧中会缺少一些日期,我相信concat函数可能会更好。

它不起作用,因为pd.concat参数的默认值为axis=0.因此,您可以按照 Dominique Paul 的建议使用axis=1调用该函数,也可以改用该函数join。下面是一个示例:

# data to create the dataframes with
data_1 = [1,2,3,4,5]
index_1 = ['a','b','c','d','e']
data_2 = [6,7,8,9,10]
index_2 = ['b','d','e','a','c']
# create dataframes
df_1 = pd.DataFrame({'data_1':data_1, 'new_index':index_1})
df_2 = pd.DataFrame({'data_2':data_2, 'new_index':index_2})
# setting new index to test unaligned indexes
df_1.set_index('new_index', inplace=True, drop=True)
df_2.set_index('new_index', inplace=True, drop=True)
# join operation is performed on indexes
df_1.join(df_2)

调用concataxis设置为1

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

我遇到了同样的问题,我用以下行解决了:

df.groupby(df.index).sum()

例如:

function  function2
a       0.1        NaN
b       0.2        NaN
b       NaN        0.2
a       NaN        0.2

成为

function  function2
a       0.1        0.2
b       0.2        0.2

最新更新