【问题标题】:Join two data frame with two columns values of a df with a single column values of another dataframe. based on some conditions?将具有 df 的两列值的两个数据框与另一个数据框的单列值连接起来。基于某些条件?
【发布时间】:2019-02-20 06:08:11
【问题描述】:

我有一个这样的数据框:

df1
col1       col2      col3      col4
 1           2        A         S
 3           4        A         P
 5           6        B         R
 7           8        B         B

我有另一个数据框:

df2
col5      col6         col3
 9         10           A
 11        12           R

如果 df1 的 col3 和 col4 的任何值与它将加入的 df2 的 col3 值匹配,我想加入这两个数据框。

最终的数据框将如下所示:

df3
col1    col2    col3    col5   col6
 1       2       A       9      10
 3       4       A       9      10
 5       6       R       11     12

如果 col3 值出现在 df2 中,那么它将通过 col3 值加入,否则如果它出现在 df2 的 col3 值中,它将通过 col4 值加入

如何使用 pandas/python 以最有效的方式做到这一点?

【问题讨论】:

  • 如果两列都匹配会发生什么?
  • 如果两个都匹配它会取第一个,我的意思是 col3

标签: python pandas dataframe


【解决方案1】:

使用带有默认内连接的双 merge,第二个过滤掉在 df3 中匹配的行,最后一个 concat 一起:

df3 = df1.drop('col4', axis=1).merge(df2, on='col3')
df4 = (df1.drop('col3', axis=1).rename(columns={'col4':'col3'})
            .merge(df2[~df2['col3'].isin(df1['col3'])], on='col3'))


df = pd.concat([df3, df4],ignore_index=True)
print (df)
   col1  col2 col3  col5  col6
0     1     2    A     9    10
1     3     4    A     9    10
2     5     6    R    11    12

编辑:使用左连接和最后一个combine_first

df3 = df1.drop('col4', axis=1).merge(df2, on='col3', how='left')
df4 = (df1.drop('col3', axis=1).rename(columns={'col4':'col3'})
            .merge(df2, on='col3', how='left'))

df = df3.combine_first(df4)
print (df)
   col1  col2 col3  col5  col6
0     1     2    A   9.0  10.0
1     3     4    A   9.0  10.0
2     5     6    B  11.0  12.0
3     7     8    B   NaN   NaN

【讨论】:

  • 如果我想让所有行都为空值,那么?
  • @KallolSamanta - 你能解释更多吗?预期输出是什么?
  • df1 的最后一行将被添加,因为 col3 和 col4 都不匹配,它将在这些字段中给出 nan 值。 df1 的 len 和最终输出 df 相同
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 2019-01-20
  • 2018-04-29
  • 1970-01-01
  • 2023-04-10
  • 2020-01-11
  • 1970-01-01
  • 2019-05-01
相关资源
最近更新 更多