根据名称列表更改 pandas 列中的文本

Posted

技术标签:

【中文标题】根据名称列表更改 pandas 列中的文本【英文标题】:Alter text in pandas column based on names list 【发布时间】:2019-12-05 17:01:04 【问题描述】:

背景

我有以下示例df

import pandas as pd
Names =    [list(['Jon', 'Mith', 'jon', 'John']),
           list(['Mark', 'Marky', 'marcs']),
           list(['Bob', 'bobby', 'Bobs'])]
df = pd.DataFrame('Text' : ['Jon J Mmith is Here and jon John from ', 
                                   'When he came Mark was Marky but not marcs so', 
                                   'I like Bob and bobby and also Bobs diner '], 

                      'P_ID': [1,2,3], 
                      'P_Name' : Names

                     )

#rearrange columns
df = df[['Text', 'P_ID', 'P_Name']]
df


    Text                                       P_ID  P_Name
0   Jon J Mmith is Here and jon John from       1   [Jon, Smith, jon, John]
1   When he came Mark was Marky but not marcs   2   [Mark, Marky, marcs]
2   I like Bob and bobby and also Bobs diner    3   [Bob, bobby, Bobs]

df 是此处Alter text in pandas column based on names 中的“旧问题”的变体。我的新df 和“新问题”的唯一区别是P_Name 列中名称的格式,如下所示:

 #old names from old question
 array(['Mmith, Jon J', 'Hider, Mary', 'Doe, Jane Ann', 'Tucker, Tom'], dtype=object) 
 #new names from new question
 array([list(['Jon', 'Smith', 'jon', 'John']),
        list(['Mark', 'Marky', 'marcs']), list(['Bob', 'bobby', 'Bobs'])], dtype=object)

目标

Text 列中,将**BLOCK** 添加到与P_Name 中找到的值相对应的值(例如[Jon, Mmith, jon, John]

问题

当我使用取自Alter text in pandas column based on names的“老问题”中的解决方案时

 df['Text'].replace(df['P_Name'].str.split(', *').apply(lambda l: ' '.join(l[::-1])),'**BLOCK**',regex=True)

我收到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-79-895f7ea46849> in <module>()
----> 1 df['Text'].replace(df['P_Name'].str.split(', *').apply(lambda l: ' '.join(l[::-1])),'**BLOCK**',regex=True)



/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
   2353             else:
   2354                 values = self.asobject
-> 2355                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   2356 
   2357         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer (pandas/_libs/lib.c:66645)()

<ipython-input-79-895f7ea46849> in <lambda>(l)
----> 1 df['Text'].replace(df['P_Name'].str.split(', *').apply(lambda l: ' '.join(l[::-1])),'**BLOCK**',regex=True)

TypeError: 'float' object is not subscriptable

期望的结果

我想要以下,类似于“老问题”Alter text in pandas column based on names中的答案

               Text                                       P_ID  P_Name
0   **BLOCK** J **BLOCK** is Here and **BLOCK** **BLOCK** from       1   [Jon, Smith, jon, John]
1   When he came **BLOCK** was **BLOCK** but not **BLOCK**         2   [Mark, Marky, marcs]
2   I like **BLOCK** and **BLOCK** and also **BLOCK** diner        3   [Bob, bobby, Bobs]

问题

鉴于我的 P_Name 列现在包含列表列表,我该如何实现我想要的结果?

【问题讨论】:

【参考方案1】:

IIUC,你需要series.replace,它以列表为参数:

to_replace :str、regex、list、dict、Series、int、float 或 None

df=df.assign(Text=df.Text.replace(df.P_Name,'**BLOCK**',regex=True))

【讨论】:

@ER_18 df['new']=df.Text.replace(df.P_Name,'**PHI**',regex=True) 完美!谢谢你:)

以上是关于根据名称列表更改 pandas 列中的文本的主要内容,如果未能解决你的问题,请参考以下文章

根据名称阻止 pandas 列中的文本

检查列中是不是存在值并根据不同条件在另一个 Pandas 中更改:Pandas

根据两列中的文本拆分行(Python,Pandas)

如何根据有序列表替换pandas dataframe列中的元素?

根据每个句子的第一个单词将 pandas 数据框列中的字符串列表分解为新列

根据 Pandas 中另一列中的索引从列中获取数据