如何从熊猫系列中的字符串中删除标点符号

问题描述

我正在尝试从熊猫系列中删除标点符号。我的问题是我无法遍历系列中的所有行。这是我尝试过的代码,但是要花很长时间才能运行。请注意,我的数据集有点大,大约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())

解决方法

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())