TfidfVectorizer in scikit-learn: ValueError: np.nan es un documento no válido


Estoy usando TfidfVectorizer de scikit-aprenda a hacer alguna extracción de características de datos de texto. Tengo un archivo CSV con una Puntuación (puede ser +1 o -1) y una Revisión (texto). Saqué estos datos en un DataFrame para poder ejecutar el Vectorizador.

Este es mi código:

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'])

Este es el rastreo del error que obtengo:

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.

He comprobado el archivo CSV y DataFrame para cualquier cosa que se está leyendo como NaN, pero no puedo encontrar nada. Hay 18000 filas, ninguna de las cuales devuelve isnan como Verdadero.

Esto es lo que df['Review'].head() parece:

  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
Author: Nickil Maveli, 2016-09-03

1 answers

Necesita convertir la cadena dtype object a unicode como se menciona claramente en el seguimiento.

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

De la página Doc de TFIDF Vectorizer:

Fit_transform (raw_documents, y=None)

Parámetros: raw_documents: iterable
un iterable que da bien str, unicode or file objects

 52
Author: Nickil Maveli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-03 16:06:27