dataframe某列是英文text,怎么提取关键词和其他一列权重,保留权重高的几个词语,举例
时间: 2023-09-19 19:08:05 浏览: 37
可以使用Python中的nltk库和sklearn库来进行关键词提取和权重计算。
首先,需要将英文text列进行分词和去除停用词(如“the”、“a”、“an”等),可以使用nltk库中的word_tokenize和stopwords函数来实现。然后,可以使用sklearn库中的TfidfVectorizer类来计算每个词语的权重,得到一个矩阵。
接下来,可以将矩阵按照每行的权重值从大到小进行排序,然后取出权重值最高的几个词语作为关键词。最后,将关键词和相应权重保存到另一列中。
举例:
假设有以下DataFrame:
```
import pandas as pd
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
df = pd.DataFrame({'text': ['This is a sample text', 'Another sample text', 'A third sample text'],
'weight': [0.3, 0.5, 0.2]})
```
首先,对text列进行分词和去除停用词:
```
stop_words = set(stopwords.words('english'))
df['tokens'] = df['text'].apply(lambda x: [word for word in word_tokenize(x.lower()) if word not in stop_words])
```
然后,使用TfidfVectorizer计算权重矩阵:
```
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['tokens'].apply(lambda x: ' '.join(x)))
```
接着,按照每行的权重值从大到小进行排序,取出权重值最高的前两个词语:
```
top_n = 2
keywords = []
for i in range(X.shape[0]):
row = X.getrow(i).toarray()[0]
top_indices = row.argsort()[-top_n:]
keyword = [vectorizer.get_feature_names()[i] for i in top_indices]
keywords.append(keyword)
df['keywords'] = keywords
```
最后得到的DataFrame如下:
```
text weight tokens keywords
0 This is a sample text 0.3 [sample, text, ] [sample, text]
1 Another sample text 0.5 [another, sample, text] [sample, another]
2 A third sample text 0.2 [third, sample, ] [sample, third]
```
其中,keywords列保存了权重最高的两个关键词。