The*_*321 6 python regex dataframe pandas
我有一个DF列,里面有很多字符串.我需要从该列中删除所有非字母数字字符:ie:
df['strings'] = ["a#bc1!","a(b$c"]
Run Code Online (Sandbox Code Playgroud)
运行代码:
Print(df['strings']): ['abc','abc']
Run Code Online (Sandbox Code Playgroud)
我试过了:
df['strings'].replace([',','.','/','"',':',';','!','@','#','$','%',"'","*","(",")","&",],"")
Run Code Online (Sandbox Code Playgroud)
但这不起作用,我觉得应该有一种更有效的方法来使用正则表达式来做到这一点.任何帮助将非常感激.
cs9*_*s95 10
使用str.replace.
df
strings
0 a#bc1!
1 a(b$c
df.strings.str.replace('[^a-zA-Z]', '')
0 abc
1 abc
Name: strings, dtype: object
Run Code Online (Sandbox Code Playgroud)
要保留字母数字字符(不仅仅是字母表符合您的预期输出所示),您还需要:
df.strings.str.replace('\W', '')
0 abc1
1 abc
Name: strings, dtype: object
Run Code Online (Sandbox Code Playgroud)
由于您编写了字母数字,因此您需要在正则表达式中添加 0-9。但也许你只想要字母...
import pandas as pd
ded = pd.DataFrame({'strings': ['a#bc1!', 'a(b$c']})
ded.strings.str.replace('[^a-zA-Z0-9]', '')
Run Code Online (Sandbox Code Playgroud)
但这基本上是 COLDSPEED 写的
| 归档时间: |
|
| 查看次数: |
10410 次 |
| 最近记录: |