python - Pandas 合并。 right_on 条件 "OR"?

标签 python pandas dataframe

我想合并 2 个数据框。关键点:我想将左侧数据框中的一列与右侧数据框中可能的 4 个不同列合并(即,如果右侧数据框中的第 1 列中不存在匹配项,则查看第 2 列等)

(可能基于条件 OR 语句)。这可能吗?

示例代码:

df3 = df1.merge(df2, left_on = 'ID', right_on = ['ID' OR 'Second ID' OR 'Third ID' OR 'Fourth ID'])```

最佳答案

将 4 列堆叠在右侧数据帧上,将此堆叠帧合并到左侧帧,然后删除重复项。

假设您有这 2 个数据帧并且有 pandas 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

关于python - Pandas 合并。 right_on 条件 "OR"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57716586/

相关文章:

python - 在不合并的情况下扩展 pandas 列

python - 如何从 Pandas DataFrame 中提取 URL?

内置 "in"算子的Python源码

python - Pygame Logo 没有改变

python - SQLAlchemy 属性错误 : 'property' object has no attribute 'translate'

python - 如何添加两个 pandas 数据框并保留两个索引

python - 如何在 x 轴上以小时和分钟格式显示所有 x 值的标签

python - 如何从 matplotlib 中的 .dat 文件读取多列,然后绘制到多个子图中

python - 如何获得一系列列表的基本统计数据?

python - 将时间四舍五入到最后 30 分钟间隔