【问题标题】:pandas: replace with a dictionary does not work with string of sentences熊猫:用字典替换不适用于句子字符串
【发布时间】:2022-01-13 08:05:35
【问题描述】:

我有一个如下的数据框:

import pandas as pd
df = pd.DataFrame({'text':['Lary Page is visiting today',' His boss, Maria Jackson is here.']})

我已提取下面列表中的名称。并使用 faker 库创建与 person_name 列表的 len 相等的假名称,并从列表中创建一个字典。

from faker import Faker
fake = Faker()

person_name = ['Lary Page', 'Maria Jackson']
fake_name= [fake.name() for n in range(len(person_name))]
name_dict = dict(zip(person_name, fake_name ))

现在我想使用字典在数据框中替换它们,但它返回错误。

df.text.str.replace(name_dict)

我想要的输出:(例如)

print(df)

Angela Mindeston is visiting today
His boss, Emanuel Smith is here.

【问题讨论】:

    标签: python pandas list dictionary replace


    【解决方案1】:

    Series.str.replaceSeries.replace 使用带有lambda 的回调:

    regex = '|'.join(r"\b{}\b".format(x) for x in name_dict.keys())
    df['text1'] = df.text.str.replace(regex, lambda x: name_dict[x.group()], regex=True)
    
    df['text2'] = df.text.replace(name_dict, regex=True)
    print (df)
                                    text                                 text1  \
    0        Lary Page is visiting today            Gary Cox is visiting today   
    1   His boss, Maria Jackson is here.   His boss, Mr. George Jones is here.   
    
                                      text2  
    0            Gary Cox is visiting today  
    1   His boss, Mr. George Jones is here.  
    

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2019-01-25
      • 2019-06-03
      • 2017-06-18
      • 2019-02-06
      相关资源
      最近更新 更多