[英]Find and replace substrings in a Pandas dataframe ignore case
df.replace('Number', 'NewWord', regex=True)
如何用 NewWord 替换Number
或number
或NUMBER
与使用标准正则表达式相同,使用i
标志。
df = df.replace('(?i)Number', 'NewWord', regex=True)
当然, df.replace
在标志必须作为正则表达式字符串(而不是标志)的一部分传递的意义上是有限制的。 如果这是使用str.replace
,您可以使用case=False
或flags=re.IGNORECASE
。
只需在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 的所有列,并将上述解决方案应用于它们。 例子:
>>> 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
野蛮。 这仅在整个字符串是'Number'
或'NUMBER'
时才有效。 它不会替换较大字符串中的那些。 当然,仅限于这两个词。
df.replace(['Number', 'NUMBER'], 'NewWord')
更多蛮力
如果不够明显,这远不如@coldspeed 的回答
import re
df.applymap(lambda x: re.sub('number', 'NewWord', x, flags=re.IGNORECASE))
或者从@coldspeed 的回答中得到提示
df.applymap(lambda x: re.sub('(?i)number', 'NewWord', x))
如果您要转换的文本位于数据框的特定列中,则此解决方案将起作用:
df['COL_n'] = df['COL_n'].str.lower()
df['COL_n'] = df['COL_n'].replace('number', 'NewWord', regex=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.