有没有一种方法可以连接两个具有共同重复索引的 Pandas 数据框,而无需进行笛卡尔积?例如:
df1 = pd.DataFrame(data={'event':['A','C','D']}, index=[1.,3.,3.])
df2 = pd.DataFrame(data={'event':['B','C']}, index=[2.,3.])
注意事件C
被记录在两个帧中,并且 C
和D
两者具有相同的索引值(时间戳)。
df1.join(df2,how='outer',lsuffix='1',rsuffix='2')
给出:
event1 event2
1.0 A NaN
2.0 NaN B
3.0 C C
3.0 D C
( C
, C
) 和 ( D
, C
) 行是 C
的笛卡尔积和D
在df1
和C
在df2
。我希望第 4 行只是( D
, NaN
),因为 D
只出现在 df1
而不是 df2
,即:
event1 event2
1.0 A NaN
2.0 NaN B
3.0 C C
3.0 D NaN
最佳答案
您需要在第二个 cumcount
索引列上进行合并
:
i, j = [
x.set_index(x.groupby(level=0).cumcount(), append=True) for x in (df1, df2)
]
i.merge(
j,
left_index=True,
right_index=True,
how='outer',
suffixes=('1', '2')
).reset_index(level=1, drop=True)
event1 event2
1.0 A NaN
2.0 NaN B
3.0 C C
3.0 D NaN
关于python - 连接两个具有共同、重复索引的 Pandas 数据框,而不进行笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49284864/