【问题标题】:Matching two columns from Pandas Dataframe but the order matters匹配 Pandas Dataframe 中的两列,但顺序很重要
【发布时间】:2021-03-04 19:48:15
【问题描述】:

我有两个DataFrames

df_1

idx A X
0   1 A
1   2 B
2   3 C
3   4 D
4   1 E
5   2 F

df_2

idx B Y 
0   1 H
1   2 I
2   4 J
3   2 K
4   3 L
5   1 M

我的目标是获得以下内容: df_result

idx A X B Y
0   1 A 1 H
1   2 B 2 I
2   4 D 4 J
3   2 F 2 K 

我正在尝试根据来自 df_2B 列同时匹配 AB 列。

AB 在到达 4 后重复它们的内容。这里的顺序很重要,因为来自 df_1 的行与 idx = 4 不匹配来自 df_2idx = 5

我正在尝试使用:

matching = list(set(df_1["A"]) & set(df_2["B"]))

然后

df1_filt = df_1[df_1['A'].isin(matching)]
df2_filt = df_2[df_2['B'].isin(matching)]

但这并没有考虑到顺序。

我正在寻找一个没有很多 for 循环的解决方案。

编辑

df_result = pd.merge_asof(left=df_1, right=df_2, left_on='idx', right_on='idx', left_by='A', right_by='B', direction='backward', tolerance=2).dropna().drop(labels='idx', axis='columns').reset_index(drop=True)

得到我想要的。

【问题讨论】:

  • 我不清楚你想要达到什么目的。索引和 A/B 列之间是否匹配?为什么 A/B == 1 的第二次出现不被视为匹配(X=E 和 Y=M)?
  • 我会尽量让它更清楚,我会编辑问题
  • 完全外连接可以达到效果

标签: python pandas


【解决方案1】:

IIUC 这应该可以工作:

df_result = df_1.merge(df_2,
            left_on=['idx', 'A'], right_on=['idx', 'B'])

【讨论】:

  • 您不需要重置索引,您可以将索引名称作为列名传递。
  • 这并没有按预期给出整个 df_result,它只输出前两行。
猜你喜欢
  • 1970-01-01
  • 2021-03-10
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 2013-03-17
相关资源
最近更新 更多