如何在Python中从dataframe列的字符串中删除非字母数字字符?

2024-06-28 15:50:37 发布

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

我有一个DF列,其中有许多字符串。我需要删除该列中的所有非字母数字字符:即:

df['strings'] = ["a#bc1!","a(b$c"]

运行代码:

Print(df['strings']): ['abc','abc']

我试过:

df['strings'].replace([',','.','/','"',':',';','!','@','#','$','%',"'","*","(",")","&",],"")

但这不起作用,我觉得应该有一个更有效的方法来使用regex。任何帮助都将不胜感激。


Tags: 方法字符串代码df字母数字字符replace
3条回答

您也可以使用regex

import re

regex = re.compile('[^a-zA-Z]')

l = ["a#bc1!","a(b$c"]

print [regex.sub('', i) for i in l]

['abc', 'abc']

使用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

要保留字母数字字符(不只是您预期的输出建议的字母表),您需要:

df.strings.str.replace('\W', '')
0    abc1
1     abc
Name: strings, dtype: object 

因为您编写的是字母数字,所以需要在regex中添加0-9。 但也许你只想按字母顺序。。。

import pandas as pd

ded = pd.DataFrame({'strings': ['a#bc1!', 'a(b$c']})

ded.strings.str.replace('[^a-zA-Z0-9]', '')

但这基本上是COLDSPEED写的

相关问题 更多 >