私は、あるjsonファイルを使用しています。
私のjsonファイルは、下のURLのjsonファイルでワインについてのレビューについてのデータで、多くの種類のワインのレビューについてリストとして記載されています。
'[https://github.com/tulip-lab/sit742/raw/master/Assessment/2019/data/wine.json']
行には”country”,"variety", "price", "point", "description"などの項目があります。
私のjsonファイルは下のような表になります。(1行が1レビューになってます。)
まず、私のjsonファイルをストップワードとして'stopwords.txt'に記載された単語を”description”から省いた状態にしました。
下のURLが'stopwords.txt'となっています。
'https://github.com/tulip-lab/sit742/raw/master/Assessment/2019/data/stopwords.txt'
そして、この、ストップワードを取り除いた”description”だけのものを”df9”と定義しました。
以下のコードで定義した”df9”のTF-IDF >0.4 となる単語とそのTF-IDFの値を出力したいと思ってます。
python
1import pandas as pd 2from nltk.tokenize import RegexpTokenizer 3 4df = pd.read_json("wine.json") 5with open('stopwords.txt') as f: 6 stop_words = f.read().splitlines() 7stop_words = set(stop_words) 8 9tokenizer = RegexpTokenizer(r"\w+(?:[-']\w+)?") 10 11def f(s): 12 tokens = tokenizer.tokenize(s) 13 return " ".join(word for word in tokens if word not in stop_words) 14 15df["description"] = df["description"].map(f) 16df.to_json("result.json") 17 18df6 = pd.read_json("result.json") 19 20df7 = df["description"] 21 22df8 = df6.query('variety == "Shiraz"') 23 24df9 = df8["description"] 25df9
そして”df9”のTF-IDF >0.4 となる単語とそのTF-IDFの値を出力するために以下のコードを書きました。
python
1from sklearn.feature_extraction.text import TfidfVectorizer 2tfidf = TfidfVectorizer(analyzer='word', stop_words = 'english') 3 4vecs = tfidf.fit_transform(df9)
その後、[https://teratail.com/questions/84025]
にあるように
python
1TF_IDF = vecs.toarray() 2terms = tfidf.get_feature_names() 3for idx, word in zip(*np.where(TF_IDF> 0.4)): 4 print("INDEX:{}, WORD:{}, TF-IDF:{}".format(idx, terms[word], TF_IDF[(idx,word)]))
という感じでコードを書いて”df9”のTF-IDF >0.4 となる単語とそのTF-IDFの値を出力しようとしたのですが、
np.where()という属性がpandasには存在しないのでエラーとなってしまいました。
なので、どのように書けば、エラーが発生せずに、”df9”のTF-IDF >0.4 となる単語とそのTF-IDFの値を出力できるのでしょうか?
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー