【问题标题】:Check if pandas column contains text in another dataframe and replace values检查 pandas 列是否包含另一个数据框中的文本并替换值
【发布时间】:2021-09-05 15:07:41
【问题描述】:

我有两个 df,一个用于用户名,另一个用于实名。我想知道如何使用另一个 df 的数据检查我的第一个 df 中是否有真名,然后替换它。 例如:

import pandas as pd
df1 = pd.DataFrame({'userName':['peterKing', 'john', 'joe545', 'mary']})
df2 = pd.DataFrame({'realName':['alice','peter', 'john', 'francis', 'joe', 'carol']})

df1
userName
0   peterKing
1   john
2   joe545
3   mary

df2
realName
0   alice
1   peter
2   john
3   francis
4   joe
5   carol

我的代码应该替换“peterKing”和“joe545”,因为这些名称出现在我的 df2.xml 文件中。我尝试使用 pd.contains,但我只能验证名称是否出现。 输出应该是这样的:

userName
0   peter
1   john
2   joe
3   mary

有人可以帮我吗?提前致谢!

【问题讨论】:

    标签: python pandas dataframe replace contains


    【解决方案1】:

    您可以使用loc[row, colum]here,您可以查看有关loc 方法的文档。和Series.str.contain 方法来选择你需要用真实姓名替换的用户名。在我看来,这个解决方案在可读性方面是明确的。

    for real_name in df2['realName'].to_list():
      df1.loc[ df1['userName'].str.contains(real_name), 'userName' ] = real_name
    

    输出:

       userName
    0   peter
    1   john
    2   joe
    3   mary
    

    【讨论】:

    • 非常感谢!这真的很有帮助!
    猜你喜欢
    • 2017-09-12
    • 2021-06-06
    • 1970-01-01
    • 2013-10-04
    • 2021-11-12
    • 2023-03-26
    • 2021-12-25
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多