【问题标题】:Adding data to columns in a dataframe based on condition on column values of another dataframe根据另一个数据框的列值的条件将数据添加到数据框中的列
【发布时间】:2021-07-22 20:23:55
【问题描述】:

我有一个输入数据框,其中 B 列有多个值: df1

    A   B         C D   E
0   a1  b1       c1 d3  e1
1   a1  b2,b3    c2 d4  e2
2   a2  b3       c3 d5  e3
3   a2  b2       c8 d6  e1
4   a2  b4,b1,b5 c4 d7  e2
5   a3  b4       c5 d3  e4
6   a4  b5       c6 d1  e5
7   a4  b6, b2   c1 d2  e1
8   a5  b6       c2 d7  e2

我希望将 df1 中 C 列和 D 列的数据添加到另一个数据框。在这种情况下,B 的列在每一行中只有 1 个值。 df2

    A   B
0   a1  b1
1   a4  b6
2   a2  b1
3   a4  b2

我想要一个输出数据框,它检查 df1 中的行,该行在 df2 中同时具有 A 和 B 的值,并从 df1 中的该行添加 C 和 D 的值。 所需的输出:

    A   B   C   D
0   a1  b1  c1  d3
1   a4  b6  c1  d2
2   a2  b1  c4  d7
3   a4  b2  c1  d2

对我来说,挑战是 df1 的 B 列中的多个值,并检查 df1 中的 2 列以在 df2 中添加 C 和 D。我该怎么做?

【问题讨论】:

  • 只是加入吗?
  • 不完全是。例如对于 df2 行 a2 b1,我们还需要在相关 df1 行中的列 B 列表中搜索,其中列 A= a2 和列 B= b4,b1,b5。由于 b1 存在,然后将 col C 和 D 值选为 c1 和 d2。

标签: python pandas dataframe


【解决方案1】:

您需要首先分解 B 列,例如在单个单元格中只有一个值而不是逗号分隔值。使用str.splitexplode B 列进行操作。然后merge

res = (
    df2.merge(df1.assign(B=lambda x: x['B'].str.split(','))
                 .explode('B')
                 [['A','B','C','D']], 
              on=['A','B'], how='left')
)
print(res)
    A   B   C   D
0  a1  b1  c1  d3
1  a4  b6  c1  d2
2  a2  b1  c4  d7
3  a4  b2  c1  d2

【讨论】:

  • 当你可以直接赋值时为什么要使用 lambda?即df1.assign(B=df1['B'].str.split(','))
  • @AnuragDabas 我认为这更像是一种习惯。你是对的,在这种情况下可以使用df1['B'] 而不是 lambda
  • 当我用于我的数据集时出现此错误:SyntaxError:keyword can't be an expression I am using this - ''' result_df = ( merge_notin_cppgear.merge(ppr_prm_peer_review_doccodes1.assign('All Projects IDs '=ppr_prm_peer_review_doccodes1['All Projects IDs'].str.split(',')).explode('All Projects IDs') [['DOC CODE','All Projects IDs','Primary Author\nLast name, First name','NEW_Author_Practice','NEW_Author_Team']], on=['DOC CODE','All Projects IDs'], how='left') )'''
  • @ShraddhaAvasthy 这是因为你不能在这里使用字符串 ('All Projects IDs') 作为名称,在我的代码中,我直接使用 B 而不使用 '。也就是说,名称中的空格是不可能的。尝试使用这种风格的字典,如.assign(**{'B':lambda x: x['B'].str.split(',')}),您将能够使用'All Projects IDs' 作为键
  • 我现在得到 "Syntaxerror: invalid syntax" result_df = (merge_notin_cppgear.merge(ppr_prm_peer_review_doccodes1.assign(**{'All Projects IDs'=lambda x: x['All Projects IDs'].str .split('; ')}).explode('All Projects IDs') [['DOC CODE','All Projects IDs','Primary Author\nLast name, First name','NEW_Author_Practice','NEW_Author_Team'] ], on=['DOC CODE','All Projects IDs'], how='left'))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多