gpt4 book ai didi

python - 基于两列比较两个数据帧并打印匹配值并对匹配值进行分组

转载 作者:行者123 更新时间:2023-12-02 02:00:21 25 4
gpt4 key购买 nike

我有两个这样的数据框,

>>df1
name key1 key2 A B
0 a1 1 K0 A0 B0
1 a2 2 K1 A1 B1
2 a3 3 K0 A2 B2
3 a3 4 K1 A3 B3

>>df2
key1 key2
0 1 K0
1 2 K0
2 3 0K
3 4 1K

我需要将 df1 的 key1,key2 与 df2 进行比较,并且必须打印匹配的行。比较时我必须检查 df1['key1','key2'] == df2['key1','key2'] 或 df1['key1','key2'] == df2['key1',reverse(' key2')]

预期输出:

>>df3
name key1 key2 A B
a1 1 K0 A0 B0
a3 3 K0 A2 B2
a3 4 K1 A3 B3
>>df4
name key1 key2 A B
a1 1 K0 A0 B0
a3 3,4 K0,K1 A2,A3 B2,B3

最佳答案

尝试:

x = df1.merge(df2, on=["key1", "key2"])
df2["key2"] = df2["key2"].str[::-1]
y = df1.merge(df2, on=["key1", "key2"])

df3 = pd.concat([x, y])
df4 = (
df3.assign(key1=df3.key1.astype(str))
.groupby("name", as_index=False)
.agg(", ".join)
)

print(df3)
print(df4)

打印:

  name  key1 key2   A   B
0 a1 1 K0 A0 B0
0 a3 3 K0 A2 B2
1 a3 4 K1 A3 B3

name key1 key2 A B
0 a1 1 K0 A0 B0
1 a3 3, 4 K0, K1 A2, A3 B2, B3

关于python - 基于两列比较两个数据帧并打印匹配值并对匹配值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69054343/

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