【问题标题】:Replace strings in entire dataframe if they are present in a list如果字符串存在于列表中,则替换整个数据框中的字符串
【发布时间】:2017-09-09 16:29:23
【问题描述】:

感谢您花时间访问我的帖子。我有以下数据框:

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")

【问题讨论】:

    标签: python list pandas dataframe replace


    【解决方案1】:

    尝试遍历列表lst,如下所示:

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

    【讨论】:

      【解决方案2】:
      df1.replace(lst, 'x' * 5, regex=True)
      
                                        col1                                 col2
      1  xxxxx is cold, canada is cold xxxxx  xxxxx is cold, canada is cold xxxxx
      2  florida, xxxxx, washington are good  florida, xxxxx, washington are good
      3    georgia, alabama, xxxxx are xxxxx  xxxxx is cold, canada is cold xxxxx
      4    xxxxx, ohio, new castle are great        hawaii, nebreska is wonderful
      5        hawaii, nebreska is wonderful    xxxxx, ohio, new castle are great
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-14
          • 1970-01-01
          • 1970-01-01
          • 2020-09-23
          • 2018-12-04
          • 2022-10-13
          相关资源
          最近更新 更多