2016-09-03 39 views
11

私はscikit-learnのTfidfVectorizerを使って、テキストデータからいくつかの特徴抽出を行っています。私はスコア(+1または-1)とレビュー(テキスト)を持つCSVファイルを持っています。このデータをDataFrameにプルして、Vectorizerを実行できるようにしました。Scikit-learnのTfidfVectorizer:ValueError:np.nanが無効なドキュメント

これは私のコードです:

import pandas as pd 
import numpy as np 
from sklearn.feature_extraction.text import TfidfVectorizer 

df = pd.read_csv("train_new.csv", 
      names = ['Score', 'Review'], sep=',') 

# x = df['Review'] == np.nan 
# 
# print x.to_csv(path='FindNaN.csv', sep=',', na_rep = 'string', index=True) 
# 
# print df.isnull().values.any() 

v = TfidfVectorizer(decode_error='replace', encoding='utf-8') 
x = v.fit_transform(df['Review']) 

これは私が取得エラーのトレースバックです:

Traceback (most recent call last): 
    File "/home/PycharmProjects/Review/src/feature_extraction.py", line 16, in <module> 
x = v.fit_transform(df['Review']) 
File "/home/b/hw1/local/lib/python2.7/site- packages/sklearn/feature_extraction/text.py", line 1305, in fit_transform 
    X = super(TfidfVectorizer, self).fit_transform(raw_documents) 
File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform 
self.fixed_vocabulary_) 
File "/home/b/work/local/lib/python2.7/site- packages/sklearn/feature_extraction/text.py", line 752, in _count_vocab 
    for feature in analyze(doc): 
File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 238, in <lambda> 
tokenize(preprocess(self.decode(doc))), stop_words) 
File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 118, in decode 
raise ValueError("np.nan is an invalid document, expected byte or " 
ValueError: np.nan is an invalid document, expected byte or unicode string. 

私がNaNとして読まれています何のためにCSVファイルやデータフレームをチェックするが、私はできます何も見つけられません。 18000行があり、いずれもTrueとしてisnanを返しません。あなたは明確にトレースバックに記載されているようunicode文字列にDTYPE objectを変換する必要があり

0 This book is such a life saver. It has been s... 
    1 I bought this a few times for my older son and... 
    2 This is great for basics, but I wish the space... 
    3 This book is perfect! I'm a first time new mo... 
    4 During your postpartum stay at the hospital th... 
    Name: Review, dtype: object 
+1

それは私にはあなたのデータフレーム内のテキストのエンコーディングに関連見た目ほどあなたが ''のdf [「レビュー」]の頭を表示することができます何よりも何か? –

+0

確かに。私は自分の投稿を編集しました。 – boltthrower

+0

また、 'type(df ['Review']。iloc [0])'? –

答えて

28

これは次のようにdf['Review'].head()が見えるものです。 TFIDFベクトライザーのドキュメントページから

x = v.fit_transform(df['Review'].values.astype('U')) ## Even astype(str) would work 

fit_transform(raw_documents, y=None)

Parameters: raw_documents : iterable
an iterable which yields either str, unicode or file objects

+1

を与えます。どうもありがとうございます。正しい答えとしてマークしてください。 – boltthrower

関連する問題