Python удаляет стоп-слова из pandas dataframe
Я хочу удалить стоп-слова из столбца "tweets". Как я повторяю каждую строку и каждый элемент?
pos_tweets = [('I love this car', 'positive'),
('This view is amazing', 'positive'),
('I feel great this morning', 'positive'),
('I am so excited about the concert', 'positive'),
('He is my best friend', 'positive')]
test = pd.DataFrame(pos_tweets)
test.columns = ["tweet","class"]
test["tweet"] = test["tweet"].str.lower().str.split()
from nltk.corpus import stopwords
stop = stopwords.words('english')
Ответы
Ответ 1
Использование List List понимая
test['tweet'].apply(lambda x: [item for item in x if item not in stop])
Возврат:
0 [love, car]
1 [view, amazing]
2 [feel, great, morning]
3 [excited, concert]
4 [best, friend]
Ответ 2
Мы можем импортировать stopwords
из nltk.corpus
, как показано ниже. При этом мы исключаем стоп-слова с пониманием списка Python и pandas.DataFrame.apply
.
# Import stopwords with nltk.
from nltk.corpus import stopwords
stop = stopwords.words('english')
pos_tweets = [('I love this car', 'positive'),
('This view is amazing', 'positive'),
('I feel great this morning', 'positive'),
('I am so excited about the concert', 'positive'),
('He is my best friend', 'positive')]
test = pd.DataFrame(pos_tweets)
test.columns = ["tweet","class"]
# Exclude stopwords with Python list comprehension and pandas.DataFrame.apply.
test['tweet_without_stopwords'] = test['tweet'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))
print(test)
# Out[40]:
# tweet class tweet_without_stopwords
# 0 I love this car positive I love car
# 1 This view is amazing positive This view amazing
# 2 I feel great this morning positive I feel great morning
# 3 I am so excited about the concert positive I excited concert
# 4 He is my best friend positive He best friend
Его также можно исключить, используя pandas.Series.str.replace
.
pat = r'\b(?:{})\b'.format('|'.join(stop))
test['tweet_without_stopwords'] = test['tweet'].str.replace(pat, '')
test['tweet_without_stopwords'] = test['tweet_without_stopwords'].str.replace(r'\s+', ' ')
# Same results.
# 0 I love car
# 1 This view amazing
# 2 I feel great morning
# 3 I excited concert
# 4 He best friend
Если вы не можете импортировать стоп-слова, вы можете загрузить их следующим образом.
import nltk
nltk.download('stopwords')
Другой способ ответа - импортировать text.ENGLISH_STOP_WORDS
из sklearn.feature_extraction
.
# Import stopwords with scikit-learn
from sklearn.feature_extraction import text
stop = text.ENGLISH_STOP_WORDS
Обратите внимание, что количество слов в секундах секундомера scikit-learn и nltk отличаются друг от друга.
Ответ 3
Проверьте pd.DataFrame.replace(), это может сработать для вас:
In [42]: test.replace(to_replace='I', value="",regex=True)
Out[42]:
tweet class
0 love this car positive
1 This view is amazing positive
2 feel great this morning positive
3 am so excited about the concert positive
4 He is my best friend positive
Изменить: replace()
будет искать строку (и даже подстроки). Напр. он заменил бы rk
на work
, если rk
- это временное слово, которое иногда не ожидается.
Следовательно, использование regex
здесь:
for i in stop :
test = test.replace(to_replace=r'\b%s\b'%i, value="",regex=True)