python - 如果字符串存在于列表中,则替换整个数据框中的字符串

标签 python list pandas dataframe replace

感谢您抽出宝贵时间访问我的帖子。我在下面有以下数据框:

df1
        col1                                    col2
    1   virginia is cold, canada is cold too    virginia is cold, canada is cold too
    2   florida, virginia, washington are good  florida, virginia, washington are good
    3   georgia, alabama, virginia are hot      virginia is cold, canada is cold too
    4   virginia, ohio, new castle are great    hawaii, nebreska is wonderful
    5   hawaii, nebreska is wonderful           virginia, ohio, new castle are great

另外,我有一个包含字符串的列表:

lst = ['virginia', 'hot', 'too']

如果它与列表中的字符串之一匹配,我想用“xxxxxx”替换整个数据框中的字符串。例如,我的数据框在替换后看起来像这样:

 df1
            col1                                    col2
        1   xxxxxx is cold, canada is cold xxxxxx   xxxxxx is cold, canada is cold xxxxxx
        2   florida, xxxxxx, washington are good    florida, xxxxxx, washington are good
        3   georgia, alabama, xxxxxx are xxxxxx     xxxxxx is cold, canada is cold xxxxxx
        4   xxxxxx, ohio, new castle are great      hawaii, nebreska is wonderful
        5   hawaii, nebreska is wonderful           xxxxxx, ohio, new castle are great

到目前为止,我已经尝试过但它不起作用:

df1 = df1.replace(lst, "xxxxxx")

最佳答案

您可以根据单词列表创建字典并使用正则表达式:

lst = ['virginia', 'hot', 'too']
df1.replace({w: "xxxxxx" for w in lst}, regex=True)

enter image description here

关于python - 如果字符串存在于列表中,则替换整个数据框中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43394148/

相关文章:

Python 将一个文件的内容复制到另一个目录中的另一个文件中

python - 在特定深度的字典上添加项目

python - 在嵌套列表中搜索

python-3.x - 使用 scipy.stats.mstats.winsorize 对我的样本进行 1% 和 99% 的 winsorize 后,我的样本的最大值仍然大于 99% 时的值

python 相当于 MATLAB 的 'replace unimportable cells with...'

python - 使用 Spacy 模式匹配器的复杂(重复)规则

python - 当我们打开子框架时如何隐藏主框架

Java - 对象映射器 - 要列出的 JSON 数字数组 <Long>

python - Pandas:具有多种功能的分组和聚合

python - 连接到 Hive 并使用 pandas 创建表