DataFrame - remove rows that contains stop words or numbers in the 'word' column

Viewed 735

I have dataframe with two columns(words, and count how those words), ordered by count:

    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

What I want, is to remove the stop words, and the numbers (like '347' and '348'). e.g. in the example, remove rows 0, 2, 6051, 6053 ('the', 'who', '347', '348').

This is how I created the 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)

I also got the stop words:

!pip install nltk
import nltk
nltk.download("stopwords")

from nltk.corpus import stopwords
stops =  set(stopwords.words('english'))

But how can I remove those stop words (and preferably the numbers) from the DataFrame?


I saw in this blog post that they managed to remove the stop words from trump's tweets dataset, but I didn't manage to make his code to work on my dataset. This is his code:

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)
1 Answers

Use pandas.Series.isin with pandas.Series.str.isnumeric to first remove words matching from the stopwords list and then exclude numeric values from Word column:

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