Alter text in pandas column based on names

前端 未结 1 1451
情话喂你
情话喂你 2020-12-22 04:49

Background

I have the following sample df

import pandas as pd
df = pd.DataFrame({\'Text\' : [\'Jon J Mmith is Here from         


        
相关标签:
1条回答
  • 2020-12-22 05:46

    One way:

    >>> df['Text'].replace(df['P_Name'].str.split(', *').apply(lambda l: ' '.join(l[::-1])),'**BLOCK**',regex=True)
    0           **BLOCK** is here from **BLOCK** until **BLOCK**
    1                                 No P_Name found here
    2                  **BLOCK** is also here until **BLOCK**
    3    **BLOCK** was **BLOCK** **BLOCK** is not here but **...
    

    You can use replace=True to do this in place, or create a new column with df['new_col']= the above. What this does is splits the P_name column, joins it in reverse with a space, and replaces it in your Text column.

    0 讨论(0)
提交回复
热议问题