且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

跳过空列表并继续执行功能

更新时间:2022-12-08 18:08:20

找到没有空列表的行,并仅在这些行上使用replace方法:

Locate the rows which do not have an empty list and use your replace method only on those rows:

# Boolean indexing the rows which do not have an empty list
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)  

输出

                                        Text  P_ID                   P_Name                                                  New
0     Jon J Smith is Here and jon John from      1  [Jon, Smith, jon, John]  **BLOCK** J **BLOCK** is Here and **BLOCK** **BLOCK** from 
1                                       Test     2                       []                                                  NaN
2  I like Bob and bobby and also Bobs diner      3       [Bob, bobby, Bobs]  I like **BLOCK** and **BLOCK** and also **BLOCK**s diner