【问题标题】:How to replace the string in the text if the string is in a list in Python?如果字符串在Python的列表中,如何替换文本中的字符串?
【发布时间】:2020-02-03 10:24:50
【问题描述】:

数据框有 2 列:句子和列表。要求是将 df['list'] 中存在的 df['sentence'] 中的字符串替换为字符串 found|present。

from pandas import DataFrame

df = {'list': [['Ford','Mercedes Benz'],['ford','hyundai','toyota'],['tesla'],[]],
        'sentence': ['Ford is less expensive than Mercedes Benz' ,'toyota and hyundai mileage is good compared to ford','tesla is an electric car','toyota too has electric cars']
        }

df = DataFrame(df,columns= ['list','sentence'])

df['sentence'] 的预期输出是:

Ford|present is less expensive than Mercedes Benz|present
toyota|present and hyundai|present mileage is good compared to ford|present
tesla|present is an electric car
toyota too has electric cars

【问题讨论】:

  • 为什么最后一项toyota too has electric cars没有被修改?
  • 因为相应的列表没有任何要替换的字符串。这是一个空列表。
  • 您尝试了哪些方法,您的方法有什么问题?

标签: python pandas list dataframe replace


【解决方案1】:

使用正则表达式替换:

(从 IPython 交互式会话中截取)

In [36]: import re                                                                                          

In [37]: def sub_from_list(row): 
    ...:     if row['list']: 
    ...:         row['sentence'] =  re.sub(r'({})'.format('|'.join(set(row['list']))), r'\1|present', row['s
    ...: entence']) 
    ...:     return row 
    ...:                                                                                                    

In [38]: df.apply(sub_from_list, axis=1)                                                                    
Out[38]: 
                      list                                           sentence
0          [Ford, hyundai]     Ford|present is expensive than hyundai|present
1  [ford, hyundai, toyota]  toyota|present and hyundai|present mileage is ...
2                  [tesla]                   tesla|present is an electric car
3                       []                       toyota too has electric cars

【讨论】:

    【解决方案2】:

    您可以使用 apply 函数和正则表达式来替换 apply 函数中的文本

    import re
    
    df = {'list': [['Ford','Mercedes Benz'],['ford','hyundai','toyota'],['tesla'],[]],
            'sentence': ['Fords is less expensive than Mercedes Benz' ,'toyota and hyundai mileage is good compared to ford','tesla is an electric car','toyota too has electric cars']
            }
    
    df = DataFrame(df,columns= ['list','sentence'])
    
    def replace_values(row):
        if len(row.list)>0:
            pat = r"(\b"+"|".join(row.list) +r")(\b)"
            print(pat)
            row.sentence = re.sub(pat, "\\1|present\\2", row.sentence)
        return row
    
    df.apply(replace_values, axis=1)
    
    

    【讨论】:

    • 最后一项 (index = 3) 被替换为 '|presentt|presento|presenty|presento|presentt|presenta|present |presentt|presento| ..
    • @ansev /Dev。谢谢你。如果我们有福特而不是福特。该词被替换为 Ford|presents。精确匹配会很好。不是吗?
    • 新代码不会取代福特,但它会取代福特的福特|present。连字符 S 在出现后添加。我正在寻找一个完全匹配的字符串。
    【解决方案3】:

    您可以在数据框上使用自定义函数,如下所示:

    代码

    import pandas as pd
    
    df = {'list': [['Ford','hyundai'],['ford','hyundai','toyota'],['tesla'],[]],
            'sentence': ['Ford is expensive than hyundai' ,'toyota and hyundai mileage is good compared to ford','tesla is an electric car','toyota too has electric cars']
            }
    
    df = pd.DataFrame(df)
    
    def rep_text(row):
        if not row.list:
            return row
        words = row.sentence.split()
        new_words = [word+'|present' \
        if word in row.list else word\
        for word in words]
    
        row['sentence'] = ' '.join(new_words)
        return row
    
    df = df.apply(rep_text, axis=1)
    

    输出

                          list                                           sentence
    0          [Ford, hyundai]     Ford|present is expensive than hyundai|present
    1  [ford, hyundai, toyota]  toyota|present and hyundai|present mileage is ...
    2                  [tesla]                   tesla|present is an electric car
    3                       []                       toyota too has electric cars
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2019-01-30
      • 2020-08-03
      • 2019-09-10
      • 2016-04-01
      相关资源
      最近更新 更多