【问题标题】:Merge 2 dfs, with the row if it is the only row that contains the word合并 2 个 dfs,如果它是唯一包含单词的行
【发布时间】:2022-12-28 13:51:39
【问题描述】:

我有 2 个熊猫数据框:

df1 = pd.DataFrame({'keyword': ['Sox','Sox','Jays','D', 'Jays'],
                   'val':[1,2,3,4,5]})

df2 = pd.DataFrame({'name': ['a b c', 'Sox Red', 'Blue Jays White Sox'],
                   'city':[f'city-{i}' for i in [1,2,3]],
                   'info': [5, 6, 7]})
>>> df1
    keyword val
0   Sox     1
1   Sox     2
2   Jays    3
3   D       4
4   Jays    5

>>> df2
    name                 city       info
0   a b c                city-1     5
1   Sox Red              city-2     6
2   Blue Jays White Sox  city-3     7

对于 df1 的每一行,合并应该采用 df1['keyword'] 的确切元素,并查看它是否存在于每个 df2['name'] 元素中(例如使用 .str.contains)。现在有以下选项:

  • 如果它恰好出现在df2['name']的一行中:将df1的当前行与df2的这一行相匹配。
  • 否则(如果它出现在 df2['name'] 的不止一行或零行中):不要将 df1 的当前行与任何内容匹配 - 值将为 NaN。

结果应如下所示:

    keyword         val name        city    info
0   Sox             1   NaN         NaN     NaN
1   Sox             2   NaN         NaN     NaN
2   Jays            3   Blue Jays   city-3  7.0
3   D               4   NaN         NaN     NaN
4   Jays            5   Blue Jays   city-3  7.0

在"team_keyword"专栏中:

  • "Sox" 匹配df2 的多行(第 1 行和第 2 行),因此它与 NaNs 合并,
  • "D"匹配0行,所以也和NaNs合并,
  • "Jays" 恰好匹配df2 中的 1 行,因此它与这一行合并。

如何使用熊猫做到这一点?

【问题讨论】:

    标签: python pandas regex dataframe merge


    【解决方案1】:

    一种方法是使用 .apply() 和 .str.contains() 的组合来查找 df2 中与 df1 中的行相匹配的行。然后,我们可以使用.merge() 合并生成的数据帧:

    def merge_dfs(row):
        keyword = row['keyword']
        df2_match = df2[df2['name'].str.contains(keyword)]
        return df2_match.iloc[0] if len(df2_match) == 1 else pd.Series(dtype='float64')
    result = df1.apply(merge_dfs, axis=1).reset_index(drop=True)
    result = df1.merge(result, left_index=True, right_index=True, how='left')
    

    这应该给出预期的结果:

    >>> result
        keyword val city    info    name
    0   Sox     1   NaN     NaN     NaN
    1   Sox     2   NaN     NaN     NaN
    2   Jays    3   city-3  7.0     Blue Jays White Sox
    3   D       4   NaN     NaN     NaN
    4   Jays    5   city-3  7.0     Blue Jays White Sox
    

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 2016-12-14
      • 2016-07-30
      • 2022-09-27
      • 2011-11-08
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多