Replace whole string if it contains substring in pandas

后端 未结 4 2238
感情败类
感情败类 2020-11-27 04:46

I want to replace all strings that contain a specific substring. So for example if I have this dataframe:

import pandas as pd
df = pd.DataFrame({\'name\': [\         


        
4条回答
  •  爱一瞬间的悲伤
    2020-11-27 04:51

    You can use str.contains to mask the rows that contain 'ball' and then overwrite with the new value:

    In [71]:
    df.loc[df['sport'].str.contains('ball'), 'sport'] = 'ball sport'
    df
    
    Out[71]:
        name       sport
    0    Bob      tennis
    1   Jane  ball sport
    2  Alice  ball sport
    

    To make it case-insensitive pass `case=False:

    df.loc[df['sport'].str.contains('ball', case=False), 'sport'] = 'ball sport'
    

提交回复
热议问题