str.翻译()方法对Pandas系列给出误差

2024-04-27 03:50:59 发布

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

我有一个3列的数据帧。我想操作的两个列是Dog_Summary和{}。这些列是字符串,我希望删除它们可能有的标点符号。

我试过以下方法:

df[['Dog_Summary', 'Dog_Description']] = df[['Dog_Summary', 'Dog_Description']].apply(lambda x: x.str.translate(None, string.punctuation))

对于上述内容,我得到一个错误信息:

^{pr2}$

我尝试的第二种方法是:

df[['Dog_Summary', 'Dog_Description']] = df[['Dog_Summary', 'Dog_Description']].apply(lambda x: x.replace(string.punctuation, ' '))

但是,它仍然不起作用!

有人能给我建议吗

谢谢!:)


Tags: 数据方法lambda字符串nonedfstringdescription
1条回答
网友
1楼 · 发布于 2024-04-27 03:50:59

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来捕获任何标点字符:

^{pr2}$

如果要将此应用于数据帧,只需按照您现在所做的操作:

df.loc[:, cols] = df[cols].apply(lambda s: s.str.replace(rf'[{punctuation}]', ''))

或者,您可以使用s.replace(rf'[{punctuation}]', '', regex=True)(不使用.str访问器)。在

相关问题 更多 >