在Pandas中使用TF-IDF提取文本特征可以通過以下步驟實(shí)現(xiàn):
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
data = {'text': ['This is a sample text for TF-IDF example',
'TF-IDF is a technique used in text mining',
'It calculates the importance of each word in a document']}
df = pd.DataFrame(data)
tfidf = TfidfVectorizer()
tfidf_matrix = tfidf.fit_transform(df['text'])
tfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns=tfidf.get_feature_names_out())
現(xiàn)在,tfidf_df中包含了每個(gè)文檔中每個(gè)單詞的TF-IDF值作為特征。您可以將這些特征用于機(jī)器學(xué)習(xí)模型中進(jìn)行文本分類、聚類等任務(wù)。