【问题标题】:Replace whole string if it contains substring in pandas如果它包含熊猫中的子字符串,则替换整个字符串
【发布时间】:2017-02-07 16:13:18
【问题描述】:

我想替换所有包含特定子字符串的字符串。例如,如果我有这个数据框:

import pandas as pd
df = pd.DataFrame({'name': ['Bob', 'Jane', 'Alice'], 
                   'sport': ['tennis', 'football', 'basketball']})

我可以像这样用字符串“ball sport”替换足球:

df.replace({'sport': {'football': 'ball sport'}})

我想要的是将包含ball(在本例中为footballbasketball)的所有内容替换为“ball sport”。像这样的:

df.replace({'sport': {'[strings that contain ball]': 'ball sport'}})

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用str.contains 屏蔽包含“ball”的行,然后用新值覆盖:

    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
    

    要使其不区分大小写,请传递 `case=False:

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

    【讨论】:

    • .contains 也接受正则表达式,因此您可以将不区分大小写的标志添加到字符串中,而不是传递case=False,例如:.str.contains(r'(?i)ball')
    【解决方案2】:

    您可以将apply 与 lambda 一起使用。 lambda 函数的x 参数将是“运动”列中的每个值:

    df.sport = df.sport.apply(lambda x: 'ball sport' if 'ball' in x else x)
    

    【讨论】:

      【解决方案3】:

      你可以使用str.replace

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

      重新分配

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

      【讨论】:

        【解决方案4】:

        不一样的str.contains

         df['support'][df.name.str.contains('ball')] = 'ball support'
        

        【讨论】:

          【解决方案5】:

          您也可以使用 lambda 函数:

          data  = {"number": [1, 2, 3, 4, 5], "function": ['IT', 'IT application', 
          'IT digital', 'other', 'Digital'] }
          df = pd.DataFrame(data)  
          df.function = df.function.apply(lambda x: 'IT' if 'IT' in x else x)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-11-22
            • 1970-01-01
            • 2018-12-05
            • 1970-01-01
            • 2016-04-09
            • 2018-10-01
            • 2020-04-05
            相关资源
            最近更新 更多