查找并替换Pandas数据帧中的子字符串忽略cas

2024-04-18 22:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何用NewWord替换Number或{}或{}


Tags: truenumberdfreplaceregexnewword
3条回答

与使用标准正则表达式相同,使用^{} flag。在

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

当然,df.replace是有限制的,标志必须作为regex字符串(而不是标志)的一部分传递。如果这是使用str.replace,那么您可以使用case=False或{}。在

只需在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

[Edit]:如果有多个列要在其中查找子字符串,则可以选择具有object数据类型的所有列,并对其应用上述解决方案。示例:

^{pr2}$

粗野的。只有当整个字符串是'Number'或{}时,这才有效。它不会替换较大字符串中的字符串。当然,它只限于这两个词。在

df.replace(['Number', 'NUMBER'], 'NewWord')

更多暴力
如果这还不够明显,那就远远不如@coldspeed的答案

^{pr2}$

或者是从@coldspeed的回答中得到提示

df.applymap(lambda x: re.sub('(?i)number', 'NewWord', x))

相关问题 更多 >