查找并替换Pandas数据框中的子字符串忽略大小写 [英] Find and replace substrings in a Pandas dataframe ignore case

查看:603
本文介绍了查找并替换Pandas数据框中的子字符串忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df.replace('Number', 'NewWord', regex=True)

如何用NewWord替换NumbernumberNUMBER

how to replace Number or number or NUMBER with NewWord

推荐答案

只需在str.replace中使用case=False.

示例:

df = pd.DataFrame({'col':['this is a Number', 'and another NuMBer', 'number']})

>>> df
                  col
0    this is a Number
1  and another NuMBer
2              number

df['col'] = df['col'].str.replace('Number', 'NewWord', case=False)

>>> df
                   col
0    this is a NewWord
1  and another NewWord
2              NewWord

:如果要在其中查找子串,请选择所有具有object dtypes的列,然后将上述解决方案应用于它们.示例:

: In the case of having multiple columns you are looking for your substring in, you can select all columns with object dtypes, and apply the above solution to them. Example:

>>> df
                  col                col2  col3
0    this is a Number  numbernumbernumber     1
1  and another NuMBer                   x     2
2              number                   y     3

str_columns = df.select_dtypes('object').columns

df[str_columns] = (df[str_columns]
                   .apply(lambda x: x.str.replace('Number', 'NewWord', case=False)))

>>> df
                   col                   col2  col3
0    this is a NewWord  NewWordNewWordNewWord     1
1  and another NewWord                      x     2
2              NewWord                      y     3

这篇关于查找并替换Pandas数据框中的子字符串忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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