数据帧 - 删除'word'列中包含非索引字或数字的行



我有一个数据帧,它有两列(单词,以及单词的计数方式(,按计数排序:

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"one_answers"348"(。例如,在该示例中,删除行0、2、6051、6053("、"谁"、"347"、"348"(

这就是我创建DataFrame:的方式

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中删除这些停止字(最好是数字(?


我在这篇博客文章中看到,他们成功地从特朗普的推文数据集中删除了停止语,但我没能让他的代码在我的数据集中工作。这是他的代码:

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)

使用pandas.Series.isinpandas.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()]

最新更新