我的数据框有两列(单词,并计算单词的数量),按计数顺序排列:
Word Count
0 the 5337
1 boy 895
2 who 5891
3 lived 3150
4 mr 3443
... ... ...
6049 manner 3256
6050 holiday 2702
6051 347 276
6052 spreading 4937
6053 348 277
我想要的是删除停用词和数字(例如“ 347”和“ 348”)。例如在示例中,删除第0、2、6051、6053行(“ the”,“ who”,“ 347”,“ 348”)。
这是我创建数据框的方式:
count_words_dict = {'the': 5337, 'boy': 895, 'who': 5891, 'lived': 3150, 'mr': 3443, 'and': 462, 'mrs': 3444, 'dursley': 1797, 'of': 3618, 'number': 3599, 'four': 2240, 'privet': 4007, 'drive': 1749, 'were': 5842, 'proud': 4034, 'to': 5431, 'say': 4397, 'that': 5336, 'they': 5346}
df = pd.DataFrame(list(count_words_dict.items()), columns = ['Word','Count'])
df.sort_values(by=['Count'], ascending=False)
df.reset_index(drop=True)
我也得到了停用词:
!pip install nltk
import nltk
nltk.download("stopwords")
from nltk.corpus import stopwords
stops = set(stopwords.words('english'))
但是如何从DataFrame中删除那些停用词(最好是数字)?
我在this blog post中看到,他们设法从特朗普的tweets数据集中删除了停用词,但是我没有设法使他的代码在我的数据集中工作。这是他的代码:
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
stops = set(stopwords.words('english')+['com'])
co = CountVectorizer(stop_words=stops)
counts = co.fit_transform(data.Tweet_Text)
pd.DataFrame(counts.sum(axis=0),columns=co.get_feature_names()).T.sort_values(0,ascending=False).head(50)
答案 0 :(得分:2)
将pandas.Series.isin
与pandas.Series.str.isnumeric
配合使用,首先从stopwords
列表中删除匹配的单词,然后从Word
列中排除数值:
count_words_dict = {'the': 5337, 'boy': 895, 'who': 5891, 'lived': 3150, 'mr': 3443, 'and': 462, 'mrs': 3444, 'dursley': 1797,
'of': 3618, 'number': 3599, 'four': 2240, 'privet': 4007, 'drive': 1749, 'were': 5842, 'proud': 4034,
'to': 5431, 'say': 4397, 'that': 5336, 'they': 5346, '345':200, '555':1000}
df = pd.DataFrame(list(count_words_dict.items()), columns = ['Word','Count'])
df.sort_values(by=['Count'], ascending=False)
df.reset_index(drop=True)
from nltk.corpus import stopwords
stops = list(stopwords.words('english'))
df = df[~df['Word'].isin(stops)]
df = df[~df['Word'].str.isnumeric()]