Replace whole string if it contains substring in pandas

后端 未结 4 2202
感情败类
感情败类 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'
    
    0 讨论(0)
  • 2020-11-27 05:07

    A different str.contains

     df['support'][df.name.str.contains('ball')] = 'ball support'
    
    0 讨论(0)
  • 2020-11-27 05:15

    You can use apply with a lambda. The x parameter of the lambda function will be each value in the 'sport' column:

    df.sport = df.sport.apply(lambda x: 'ball sport' if 'ball' in x else x)
    
    0 讨论(0)
  • 2020-11-27 05:16

    you can use str.replace

    df.sport.str.replace(r'(^.*ball.*$)', 'ball sport')
    
    0        tennis
    1    ball sport
    2    ball sport
    Name: sport, dtype: object
    

    reassign with

    df['sport'] = df.sport.str.replace(r'(^.*ball.*$)', 'ball sport')
    df
    

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