在Pandas中使用TF-IDF提取文本特征可以通過以下步驟實現:
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())
現在,tfidf_df中包含了每個文檔中每個單詞的TF-IDF值作為特征。您可以將這些特征用于機器學習模型中進行文本分類、聚類等任務。