Pet*_*ush 6 python regex string dataframe pandas
df.replace('Number', 'NewWord', regex=True)
Run Code Online (Sandbox Code Playgroud)
如何用 NewWord替换Numberornumber或NUMBER
与使用标准正则表达式相同,使用iflag。
df = df.replace('(?i)Number', 'NewWord', regex=True)
Run Code Online (Sandbox Code Playgroud)
当然,df.replace在标志必须作为正则表达式字符串(而不是标志)的一部分传递的意义上是有限制的。如果这是使用str.replace,您可以使用case=False或flags=re.IGNORECASE。
只需case=False在str.replace.
例子:
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
Run Code Online (Sandbox Code Playgroud)
[编辑]:如果您要在多个列中查找子字符串,则可以选择所有具有objectdtypes 的列,并将上述解决方案应用于它们。例子:
>>> 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
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2522 次  |  
        
|   最近记录:  |