【问题标题】:Replace values in python pandas column based on second df根据第二个df替换python pandas列中的值
【发布时间】:2018-04-05 15:32:10
【问题描述】:

我已经解决了关于 stackoverflow 的所有类似问题,但这些解决方案仍然对我不起作用。

我有两个 dfs:

df1:
User_ID |    Code_1
123           htrh
345           NaN
567           cewr
...

df2:
User_ID |    Code_2
123           ert
345           nad

我想根据 User_ID 将 df1.Code_1 替换为 df2.Code_2。请注意,df2 是 df1 的 user_ids 的子集。

我试过了

df1['Code_1'] = df1['User_ID'].replace(df2.set_index('User_ID')['Code_2'])

我试过了

df1.loc[df1.User_ID.isin(df2.User_ID), ['Code_1']] = df2[['Code_2']]

两者都不起作用。没有任何改变。

预期输出:

df1:
    User_ID |    Code_1
    123           ert
    345           nad
    567           cewr
    ...

谢谢

【问题讨论】:

  • 你能发布预期的输出吗?

标签: python pandas replace syntax


【解决方案1】:

使用DataFrame.update。在调用函数之前,id 列(User_ID)和代码列(Code_1Code_2)在数据帧中应该具有相同的名称。

df2.columns = ['User_ID', 'Code_1']
df1.update(df2)

这对于您的情况应该足够了。其他用途请咨询documentation

【讨论】:

    【解决方案2】:

    你可以使用 combine_first

    df2.set_index('User_ID').Code_2.combine_first(df1.set_index('User_ID').Code_1)
    
    
    User_ID
    123     ert
    345     nad
    567    cewr
    

    【讨论】:

      【解决方案3】:

      您可以使用pd.Series.map + pd.Series.fillna

      df1['Code_1'] = df1['User_ID'].map(df2.set_index('User_ID')['Code_2'])\
                                    .fillna(df1['Code_1'])
      
      print(df1)
      
      #    User_ID Code_1
      # 0      123    ert
      # 1      345    nad
      # 2      567   cewr
      

      这个想法是在执行映射时对齐索引,如果df2 中不存在映射,则使用原始值填充。

      【讨论】:

      • 对我来说,看起来 pd.DataFrame.update 完全符合要求,更易于理解,可以一次更新多个列,并且由于参数的存在可以更普遍地使用.
      • @mcard,你的回答很好,我赞成。我认为选择哪个答案与任何事情一样多是个人喜好。
      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 2023-01-26
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 2018-11-11
      相关资源
      最近更新 更多