Skip to main content
 首页 » 编程设计

python之是否有比此代码更快的替代方法来删除 Pandas 中的停用词和标点符号

2024年11月24日9TianFang

我使用的代码似乎太慢了,也许有替代方案。

在 Pandas 中,我标记了数据框列“描述”并制作了一个要删除的停用词和标点符号列表,然后尝试删除无用的词。

import numpy as np 
import pandas as pd 
import nltk 
import string 
nltk.download("stopwords") 
nltk.download('punkt') 
 
df2 = pd.read_csv('xxx') 

在清理等之后,最终得到大约 135.000 行并且没有空值

description points  price 
0   This tremendous 100% varietal wine hails from ...   96  235.0 
1   Ripe aromas of fig, blackberry and cassis are ...   96  110.0 
2   Mac Watson honors the memory of a wine once ma...   96  90.0 
3   This spent 20 months in 30% new French oak, an...   96  65.0 
4   This is the top wine from La Bégude, named aft...   95  66.0 

然后分词

df2['description'] = df2.apply(lambda row:  
nltk.word_tokenize(row['description']), axis=1) 
df2.head() 

tokenize 非常快。现在定义无用的词:

useless_words = nltk.corpus.stopwords.words("english") +  
list(string.punctuation) 

现在尝试使用相同的技巧从 df2['description'] 中删除无用的词

df2['description'] = df2.apply(lambda row: [word for word in  
df2['description'] if not word in useless_words], axis=1) 

我预计这会更快,但需要时间来计算。我是编码的新手,所以我想也许你们知道一种替代方法来处理这个问题并减少计算时间。也可能我没有做对,我不知道,所以我提前询问并感谢。

请您参考如下方法:

你试过吗?

df2["description"] = df2["description"].str.lower() 
df2["description"] = df2["description"].str.replace("|".join(useless_words), "")