删除Pandas中的标点符号

2024-09-28 17:16:08 发布

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

code: df['review'].head()
        index         review
output: 0      These flannel wipes are OK, but in my opinion

我想从数据框的列中删除标点符号并创建一个新列。

code: import string 
      def remove_punctuations(text):
          return text.translate(None,string.punctuation)

      df["new_column"] = df['review'].apply(remove_punctuations)

Error:
  return text.translate(None,string.punctuation)
  AttributeError: 'float' object has no attribute 'translate'

我正在使用Python2.7。任何建议都会有帮助的。


Tags: textnonedfoutputstringindexreturncode
3条回答

您可以使用string模块的标点符号列表构建正则表达式:

df['review'].str.replace('[{}]'.format(string.punctuation), '')

我通过在字符串中循环使用标点符号解决了这个问题

def remove_punctuations(text):
    for punctuation in string.punctuation:
        text = text.replace(punctuation, '')
    return text

你可以像调用函数一样调用它,它应该可以工作。

df["new_column"] = df['review'].apply(remove_punctuations)

使用Pandas str.replace和regex:

df["new_column"] = df['review'].str.replace('[^\w\s]','')

相关问题 更多 >