背景
我有以下示例df
import pandas as pd
Names = [list(['Jon', 'Smith', 'jon', 'John']),
list(['Mark', 'Marky', 'marcs']),
list(['Bob', 'bobby', 'Bobs'])]
df = pd.DataFrame({'Text' : ['Jon J Smith 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 Smith 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(['Smith, Jon J', 'Rider, 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
列中,将**PHI**
添加到与[Jon, Smith, jon, John]
中找到的值相对应的值(例如P_Name
)
问题
在Alter text in pandas column based on names的“旧问题”中使用解决方案时
df['Text'].replace(df['P_Name'].str.split(', *').apply(lambda l: ' '.join(l[::-1])),'**PHI**',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])),'**PHI**',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])),'**PHI**',regex=True)
TypeError: 'float' object is not subscriptable
所需结果
我想要以下内容,类似于“旧问题” Alter text in pandas column based on names
中的答案 Text P_ID P_Name
0 **PHI** J **PHI** is Here and **PHI** **PHI** from 1 [Jon, Smith, jon, John]
1 When he came **PHI** was **PHI** but not **PHI** 2 [Mark, Marky, marcs]
2 I like **PHI** and **PHI** and also **PHI** diner 3 [Bob, bobby, Bobs]
问题
考虑到我的P_Name
列现在包含列表列表,我如何实现预期的结果?
答案 0 :(得分:1)
IIUC,您需要series.replace
,它将列表作为arg:
to_replace:str,regex,list,dict,Series,int,float或None
df=df.assign(Text=df.Text.replace(df.P_Name,'**PHI**',regex=True))