我想合并2个数据框。 The Kicker:我想将左侧数据框中的一列与右侧数据框中的可能4个不同的列合并(即,如果匹配不存在于右侧数据帧的第1列中,则查看第2列,依此类推)< / p>
(可能基于条件OR语句)。这可能吗?
示例代码:
df3 = df1.merge(df2, left_on = 'ID', right_on = ['ID' OR 'Second ID' OR 'Third ID' OR 'Fourth ID'])```
答案 0 :(得分:0)
您将4列堆叠在右侧数据帧上,将此堆叠的帧合并到左侧帧,然后删除重复项。
假设您拥有这2个数据框,并且熊猫v0.25或更高版本(对于explode
):
df1 =
ID Value
0 A 0
1 B 1
2 C 2
3 D 3
4 E 4
5 F 5
df2 =
ID1 ID2 ID3 ID4 AnotherValue
0 L G N Y 1
1 H U B F 4
2 O Z Q V 1
3 H A T P 6
4 V K A G 3
5 E C N U 1
代码:
# Combine values from 4 columns into a single row
s = df2.loc[:, 'ID1':'ID4'].apply(list, axis=1)
# Stack the 4 columns to form the right frame
right = df2.join(s.explode().rename('RightID'))
# reset_index: so that we have something to identify each unique row later
# merge: merge with the right frame
# drop_duplicate: each row in `df1` only matches to one row in `right`
df1.reset_index() \
.merge(right, left_on='ID', right_on='RightID') \
.drop_duplicates('index')
结果:
index ID Value ID1 ID2 ID3 ID4 AnotherValue RightID
0 0 A 0 H A T P 6 A
2 1 B 1 H U B F 4 B
3 2 C 2 E C N U 1 C
4 4 E 4 E C N U 1 E
5 5 F 5 H U B F 4 F