Background
The following is a minor change from 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 []
The code below works
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)
And does the following
1) uses the name in P_Name
to block the corresponding text in the Text
column by placing **BLOCK**
2) produces a new column New
This is shown below
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
Problem
However, this code works a little "too well."
Using ['his','he']
from P_Name
to block Text
:
Example: one day he and his cheated
becomes one day **BLOCK** and **BLOCK** c**BLOCK**ated
Desired: one day he and his cheated
becomes one day **BLOCK** and **BLOCK** cheated
In this example, I would like cheated
to stay as cheated
and not become c**BLOCK**ated
Desired Output
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
Question
How do I achieve my desired output?