我有一个 3 列的 DataFrame。我希望使用的 2 个列是 Dog_Summary 和 Dog_Description。这些列是字符串,我希望删除它们可能包含的任何标点符号。
我尝试了以下方法:
df[['Dog_Summary', 'Dog_Description']] = df[['Dog_Summary', 'Dog_Description']].apply(lambda x: x.str.translate(None, string.punctuation))
对于上述我得到一个错误说:
ValueError: ('deletechars is not a valid argument for str.translate in python 3. You should simply specify character deletions in the table argument', 'occurred at index Summary')
我尝试的第二种方法是:
df[['Dog_Summary', 'Dog_Description']] = df[['Dog_Summary', 'Dog_Description']].apply(lambda x: x.replace(string.punctuation, ' '))
但是还是不行!
谁能给我建议或建议
谢谢! :)
请您参考如下方法:
I wish to remove any punctuation it may have.
为此,您可以使用正则表达式和 string.punctuation:
>>> import pandas as pd
>>> from string import punctuation
>>> s = pd.Series(['abcd$*%&efg', ' xyz@)$(@rst'])
>>> s.str.replace(rf'[{punctuation}]', '')
0 abcdefg
1 xyzrst
dtype: object
.str.replace() 的第一个参数可以是正则表达式。在这种情况下,您可以使用 f 字符串和 character class捕捉任何标点字符:
>>> rf'[{punctuation}]'
'[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]' # ' and \ are escaped
如果你想将它应用到 DataFrame,只需按照你现在正在做的:
df.loc[:, cols] = df[cols].apply(lambda s: s.str.replace(rf'[{punctuation}]', ''))
或者,您可以使用 s.replace(rf'[{punctuation}]', '', regex=True)(无 .str 访问器)。
