【问题标题】:How do I remove punctuation from a string in a pandas Series如何从熊猫系列中的字符串中删除标点符号
【发布时间】:2021-01-11 22:30:26
【问题描述】:

我正在尝试从熊猫系列中删除标点符号。我的问题是我无法遍历系列中的所有行。这是我尝试过的代码,但它需要很长时间才能运行。请注意,我的数据集有点大,大约 112MB(200,000 行)

import pandas as pd
import string

df = pd.read_csv('let us see.csv')
s = set(string.punctuation)

for st in df.reviewText.str:
    for j in s:
        if j in st:
            df.reviewText = df.reviewText.str.replace(j, '')

df.reviewText = df.reviewText.str.lower()
df['clean_review'] = df.reviewText
print(df.clean_review.tail())

【问题讨论】:

  • 你为什么要迭代这个系列?您可以一次替换整个系列for j in s: df.reviewText.str.replace(j, "") 并替换所有出现的事件,而无需事先检查。
  • 你是对的。谢谢你。但它不起作用。标点符号还在
  • 如果要替换原地的值,需要使用inplace=True (pandas.pydata.org/pandas-docs/stable/reference/api/…)
  • 知道了。上帝保佑。非常感谢你有美好的一天

标签: python pandas dataframe data-mining data-cleaning


【解决方案1】:

D-E-N 的回答非常好。我只是添加了另一种如何提高代码性能的解决方案。 迭代您的系列的列表版本应该比您的方法更快。

import pandas as pd
import string

def replace_chars(text, chars):
    for c in chars:
        text = text.replace(c, '')
    return text.lower()

df = pd.read_csv('let us see.csv')
s = set(string.punctuation)

reviewTextList = df.reviewText.astype(str).tolist()
reviewTextList = [replace_chars(x, s) for x in reviewTextList]

df['clean_review'] = reviewTextList
print(df.clean_review.tail())

【讨论】:

  • 我真的很感激。太感谢了。不过还有一件事。你能帮我在我的 df['reviewText'] 列中使用 value_counts() 吗?我想检查每个单词在系列中出现的次数。我应该使用 groupby 吗?如果是,那么我如何分别迭代每一行?截图示例:imgur.com/HzjMWlc
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 2021-09-25
  • 1970-01-01
  • 2020-08-11
  • 2016-10-21
  • 2017-02-08
  • 2017-10-01
  • 1970-01-01
相关资源
最近更新 更多