【发布时间】:2019-12-27 05:34:57
【问题描述】:
背景
我有以下df,其中包含标记化的Text 和P_Name 列,是including word boundary in string modification to be more specific 的修改
P_Name = [list(['Steven', 'I','Jobs']),
list(['A', 'Ma', 'Mary']),
list(['U','Kar', 'Jacob'])]
Text = [list(['Steven', 'I','Jobs', 'likes', 'apples','I', 'too']),
list(['A','i', 'like', 'A', 'lot', 'of','sports','cares', 'A', 'Ma', 'Mary']),
list(['the','U', 'Kar', 'Jacob', 'what', 'about', 'U', 'huh','?'])]
import pandas as pd
df = pd.DataFrame({'Text' : Text,
'P_ID': [1,2,3],
'P_Name' : P_Name,
})
df
P_ID P_Name Text
0 1 [Steven, I, Jobs] [Steven, I, Jobs, likes, apples, I, too]
1 2 [A, Ma, Mary] [A, i, like, A, lot, of, sports, cares, A, Ma, Mary]
2 3 [U, Kar, Jacob] [the, U, Kar, Jacob, what, about, U, huh, ?]
目标
1) 使用P_Name 中的名称通过放置**block** 来阻止Text 列中的相应文本
2) 产生一个新列New_Text
试过
来自including word boundary in string modification to be more specific
我已经修改了代码并尝试了以下
df['New_Text']=[pd.Series(x).replace(dict.fromkeys(y,'**block**') ).str.cat(sep=' ')for x , y in zip(df['Text'],df['P_Name'])]
这与我想要的很接近,但不完全是因为有些字母被不恰当地标记为**block** 例如I 在行中0
P_ID P_Name Text New_Text
0 [**block**, **block**, **block**, likes, apples, **block**, too]
1 [**block**, i, like, **block**, lot, of, sports, cares, **block**, **block**, **block**]
2 [the, **block**, **block**, **block**, what, about, **block**, huh, ?]
期望的输出
P_ID P_Name Text New_Text
0 [**block**, **block**, **block**, likes, apples, I, too]
1 [A, i, like, A, lot, of, sports, cares, **block**, **block**, **block**]
2 [the, **block**, **block**, **block**, what, about, U, huh, ?]
问题
如何进一步修改
df['New_Text']=[pd.Series(x).replace(dict.fromkeys(y,'**block**') ).str.cat(sep=' ')for x , y in zip(df['Text'],df['P_Name'])]
或者使用新代码来实现我想要的输出?
【问题讨论】:
标签: python string pandas text replace