【发布时间】:2019-12-07 07:50:14
【问题描述】:
背景
以下是对modification of skipping empty list and continuing with function的小改动
import pandas as pd
Names = [list(['ann']),
list([]),
list(['elisabeth', 'lis']),
list(['his','he']),
list([])]
df = pd.DataFrame({'Text' : ['ann had an anniversery today',
'nothing here',
'I like elisabeth and lis 5 lists ',
'one day he and his cheated',
'same here'
],
'P_ID': [1,2,3, 4,5],
'P_Name' : Names
})
#rearrange columns
df = df[['Text', 'P_ID', 'P_Name']]
df
Text P_ID P_Name
0 ann had an anniversery today 1 [ann]
1 nothing here 2 []
2 I like elisabeth and lis 5 lists 3 [elisabeth, lis]
3 one day he and his cheated 4 [his, he]
4 same here 5 []
下面的代码有效
m = df['P_Name'].str.len().ne(0)
df.loc[m, 'New'] = df.loc[m, 'Text'].replace(df.loc[m].P_Name,'**BLOCK**',regex=True)
然后执行以下操作
1) 使用P_Name 中的名称通过放置**BLOCK** 来阻止Text 列中的相应文本
2) 产生一个新列New
如下图所示
Text P_ID P_Name New
0 **BLOCK** had an **BLOCK**iversery today
1 NaN
2 I like **BLOCK** and **BLOCK** 5 **BLOCK**ts
3 one day **BLOCK** and **BLOCK** c**BLOCK**ated
4 NaN
问题
但是,这段代码运行起来有点“太好了”。
使用来自P_Name 的['his','he'] 来阻止Text:
示例:one day he and his cheated 变为 one day **BLOCK** and **BLOCK** c**BLOCK**ated
期望:one day he and his cheated 变为 one day **BLOCK** and **BLOCK** cheated
在这个例子中,我希望cheated 保持cheated 而不是c**BLOCK**ated
期望的输出
Text P_ID P_Name New
0 **BLOCK** had an anniversery today
1 NaN
2 I like **BLOCK** and **BLOCK**5 lists
3 one day **BLOCK** and **BLOCK** cheated
4 NaN
问题
如何实现我想要的输出?
【问题讨论】:
标签: python-3.x string pandas text replace