from sklearn.feature_extraction.text import TfidfTransformer
# TF-IDF 값 출력
tfidf_vectorizer = TfidTransformer()
tf_idf_vect = tfidf_vectorizer.fit_transform(bow=vect)
tf_idf_vect.shape
tf_idf_vect[0]
tf_idf_vect[0].toarray().shape
# 벡터를 단어로 맵핑
invert_index_vectorizer = {v:k for k,v in vect.vocabulary_.items()}
invert_index_vectorizer
# TF-IDF 값이 가장 높은 단어 출력
np.argsort(tf_idf_vect[0].toarray())[0][-3:] #0번째 카테고리 중 가장 높은 tf-idf 값의 행들이 index로 출력
np.argsort(tf_idf_vect.toarray())[:, -3:] #모든 카테고리 들의 가장 중요한 단어 3개씩 출력
# 기존 dataframe 에 붙여서 출력
top_3_word = np.argsort(tf_idf_vect.toarray())[:, -3:]
df['important_word_indexes']=pd.Series(top_3_word.tolist()) #가장 높은 vector 3개를 칼럼에 추가 가능
# vector 에 따른 단어 3개씩 불러와서 출력
def convert_to_word(x):
word_list =[]
for word in x:
word_list.append(invert_index_vectorizer[word])
return word_list
df['important_words']=df['important_word_indexes'].apply(lambda x : conver_to_word(x))
df.head()