gpt4 book ai didi

python - 连接非齐次 Pandas 多重索引

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:41 25 4
gpt4 key购买 nike

import pandas as pd

d1 = {'A': ['a'],
'B1': ['b1'],
'C1': ['c1']}

d2 = {'A': ['a'],
'B2': ['b2'],
'C2': ['c2']}

df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

df1.set_index(['A', 'B1'], inplace=True)
df2.set_index(['A', 'B2'], inplace=True)

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

print(df)

我得到输出:

       C1   C2
A B1
a b1 c1 NaN
b2 NaN c2

但是,我想要

                 C1    C2  
A B1 B2
a b1 NaN c1 NaN
a NaN b2 NaN c2

Pandas 中连接多重索引的规则是什么?

怎样才能得到我想要的结果?

最佳答案

更新:处理重复的列:

In [39]: pd.concat([df1.reset_index(),df2.reset_index()])\
....: .set_index(pd.unique(df1.index.names + df2.index.names).tolist())
Out[39]:
C1 C2
A B1 B2
a b1 NaN c1 NaN
NaN b2 NaN c2

旧答案:

In [259]: pd.concat([df1.reset_index(), df2.reset_index()]).set_index(df1.index.names + df2.index.names)
Out[259]:
C F
A B D E
a b NaN NaN c NaN
NaN NaN d e NaN f

或者,您可以尝试 merge(),假设 df1 为空:

df1.reset_index().merge(df2.reset_index(), left_index=True, right_index=True, how='left').set_index(df1.index.names + df2.index.names)

关于python - 连接非齐次 Pandas 多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36815226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com