如果列表中存在字符串,则替换整个数据帧中的字符串

时间:2017-04-13 13:52:26

标签: 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")

3 个答案:

答案 0 :(得分:3)

return "\\u" + char.charCodeAt(0).toString(16)

答案 1 :(得分:3)

您可以从单词列表创建字典并使用 regex

mv shared/coverage.txt shared

enter image description here

答案 2 :(得分:2)

尝试迭代列表lst,如下所示:

import pandas as pd

...
lst = ['virginia', 'hot', 'too']
for s in lst:
    df1.replace(s, 'xxxxx', inplace=True)

print( df1)