连接两个数据帧并从索引创建多索引

Concat two dataframes and create multi-index from indexes

我有两个数据帧df_1df_2是:

df_1 = pd.DataFrame({"A1":"1", "A2":"2", "A3":"3"}, index=[2411])
df_1.index.name = "i_1"
df_2 = pd.DataFrame({"B1":"4", "B2":"5", "B3":"6"}, index=[123122])
df_2.index.name = "i_2"

我想连接它们,所以最终的 DataFrame 看起来像:

                A1  A2  A3  B1  B2  B3
i_1     i_2                     
2411    123122  1   2   3   4   5   6

基本上,这是沿轴 1 的连接,并将设置从索引移动到多索引。

我做的最接近期望的结果是:

df_1 = df_1.reset_index()
df_2 = df_2.reset_index()
df_f = pd.concat([df_1,df_2], axis=1)
df_f = pd.DataFrame(df_f, index=pd.MultiIndex.from_arrays([float(df_1["i_1"]), float(df_2["i_2"])], names=["i_1","i_2"]))
del df_f["i_1"]
del df_f["i_2"]

但结果是:

A1  A2  A3  B1  B2  B3
i_1 i_2                     
2411.0  123122.0    NaN NaN NaN NaN NaN NaN

我认为最简单的是reset_index of both df for default indexes, so concat align data nice and last set_index:

df_f = pd.concat([df_1.reset_index(),df_2.reset_index()], axis=1).set_index(['i_1','i_2'])
print (df_f)
            A1 A2 A3 B1 B2 B3
i_1  i_2                     
2411 123122  1  2  3  4  5  6

你的解决方案是不同索引的问题,所以在 concat 得到 2 行之后,因为数据不能对齐(不同的索引):

df_f = pd.concat([df_1,df_2], axis=1)
print (df_f)
         A1   A2   A3   B1   B2   B3
2411      1    2    3  NaN  NaN  NaN
123122  NaN  NaN  NaN    4    5    6

然后获取 NaNs 因为在 DataFrame 构造函数中创建新的 Multiindex 但数据不再对齐 - 在原始 df_f 中数据大小为 (2x6) 并且想要分配给 1,6 结构,索引也不同。