在python中合并两个键上的两个数据帧

2024-04-20 11:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧。我想把它们合并到键typeA和typeB上。我想在两个键中的任何一个上合并它们

# df_a
  typeA typeB value
0   b    a      3
1   c    d      4


# df_b
  typeA typeB value
0   a   b       1
1   c   d       2
pd.merge(df_a,df_b,on=['typeA','typeB'])
typeA   typeB   value_x value_y
0   c   d        4            2

但我想要的结果是

^{pr2}$

只要类型对匹配,我就把它们合并在一起。那意味着我想要

   (df_a['typeA']=df_b['typeA'] And df_a['typeB']=df_b['typeB']) or (df_a['typeA']=df_b['typeB'] And df_a['typeB']=df_b['typeA'])

我认为可以通过切换df_b的列名并再次执行merge process来完成。然后将两个合并结果合并在一起。只是想知道有没有更有效的方法来解决这个问题。在


Tags: orand数据方法类型dfvalueon
1条回答
网友
1楼 · 发布于 2024-04-20 11:30:06

一种可能的解决方案是sorted列,用于merge之前的联接:

df_a[['typeA','typeB']] = df_a[['typeA','typeB']].apply(sorted, axis=1)
df_b[['typeA','typeB']] = df_b[['typeA','typeB']].apply(sorted, axis=1)
print (df_a)
  typeA typeB  value
0     a     b      3
1     c     d      4

print (df_b)
  typeA typeB  value
0     a     b      1
1     c     d      2

df1 = pd.merge(df_a,df_b,on=['typeA','typeB'])
print (df1)
  typeA typeB  value_x  value_y
0     a     b        3        1
1     c     d        4        2

相关问题 更多 >