如果整个字符串包含pandas中的子字符串,则替换它

时间:2016-09-29 11:05:30

标签: python pandas

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

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

我可以用这样的字符串'ball sport'替换足球:

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

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

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

4 个答案:

答案 0 :(得分:20)

您可以使用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'

答案 1 :(得分:7)

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

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

答案 2 :(得分:4)

您可以使用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

enter image description here

答案 3 :(得分:1)

另一个str.contains

 df['support'][df.name.str.contains('ball')] = 'ball support'
相关问题