如果整个字符串包含pandas中的子字符串,请替换整个字符串 [英] Replace whole string if it contains substring in pandas

查看:165
本文介绍了如果整个字符串包含pandas中的子字符串,请替换整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换所有包含特定子字符串的字符串.因此,例如,如果我有此数据框:

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': ['Bob', 'Jane', 'Alice'], 
                   'sport': ['tennis', 'football', 'basketball']})

我可以用字符串"ball sport"代替足球,如下所示:

I could replace football with the string 'ball sport' like this:

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

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

What I want though is to replace everything that contains ball (in this case football and basketball) with 'ball sport'. Something like this:

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

推荐答案

您可以使用

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

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

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

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

这篇关于如果整个字符串包含pandas中的子字符串,请替换整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆