2016-03-27 13 views
1

ファイル "ratings.dat"で以下のコードを実行すると、 "ValueError"が発生します。私は別のファイルで同じコードを "、"をセパレータとして使ってみましたが、何の問題もありませんでした。しかし、セパレータが "::"のときはパンダが故障しているようです。"::"セパレータのread_csvのPandasの値エラー

コードを間違って入力していますか?

コード:

import pandas as pd 
import numpy as np 

r_cols = ['userId', 'movieId', 'rating'] 
r_types = {'userId': np.str, 'movieId': np.str, 'rating': np.float64} 
ratings = pd.read_csv(
     r'C:\\Users\\Admin\\OneDrive\\Documents\\_Learn!\\' 
     r'Learn Data Science\\Data Sets\\MovieLens\\ml-1m\\ratings.dat', 
     sep='::', names=r_cols, usecols=range(3), dtype=r_types 
     ) 

m_cols = ['movieId', 'title'] 
m_types = {'movieId': np.str, 'title': np.str} 
movies = pd.read_csv(
     r'C:\\Users\\Admin\\OneDrive\\Documents\\_Learn!\\' 
     r'Learn Data Science\\Data Sets\\MovieLens\\ml-1m\\movies.dat', 
     sep='::', names=m_cols, usecols=range(2), dtype=m_types 
     ) 

ratings = pd.merge(movies, ratings) 
ratings.head() 

"ratings.dat"

1::1287::5::978302039 
1::2804::5::978300719 
1::594::4::978302268 
1::919::4::978301368 
1::595::5::978824268 

エラー出力:

---------------------------------------------------------------------------ValueError        Traceback (most recent call last)<ipython-input-19-a2649e528fb9> in <module>() 
     7   r'C:\\Users\\Admin\\OneDrive\\Documents\\_Learn!\\' 
     8   r'Learn Data Science\\Data Sets\\MovieLens\\ml-1m\\ratings.dat', 
----> 9   sep='::', names=r_cols, usecols=range(3), dtype=r_types 
    10  ) 
    11 
C:\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, header, index_col, names, prefix, skiprows, skipfooter, skip_footer, na_values, true_values, false_values, delimiter, converters, dtype, usecols, engine, delim_whitespace, as_recarray, na_filter, compact_ints, use_unsigned, low_memory, buffer_lines, warn_bad_lines, error_bad_lines, keep_default_na, thousands, comment, decimal, parse_dates, keep_date_col, dayfirst, date_parser, memory_map, float_precision, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format, skip_blank_lines) 
    496      skip_blank_lines=skip_blank_lines) 
    497 
--> 498   return _read(filepath_or_buffer, kwds) 
    499 
    500  parser_f.__name__ = name 
C:\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 
    273 
    274  # Create the parser. 
--> 275  parser = TextFileReader(filepath_or_buffer, **kwds) 
    276 
    277  if (nrows is not None) and (chunksize is not None): 
C:\Anaconda3\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds) 
    584 
    585   # might mutate self.engine 
--> 586   self.options, self.engine = self._clean_options(options, engine) 
    587   if 'has_index_names' in kwds: 
    588    self.options['has_index_names'] = kwds['has_index_names'] 
C:\Anaconda3\lib\site-packages\pandas\io\parsers.py in _clean_options(self, options, engine) 
    663       msg += " (Note the 'converters' option provides"\ 
    664        " similar functionality.)" 
--> 665      raise ValueError(msg) 
    666     del result[arg] 
    667 
ValueError: Falling back to the 'python' engine because the 'c' engine does not support regex separators, but this causes 'dtype' to be ignored as it is not supported by the 'python' engine. (Note the 'converters' option provides similar functionality.) 

答えて

3

あなたは最後の行を読んでいる場合あなたがなぜそれが失敗しているのかの答えを得るかもしれません。私はそれを2行に吐きました。

ValueError: Falling back to the 'python' engine because the 'c' engine does not support regex separators,

but this causes 'dtype' to be ignored as it is not supported by the 'python' engine. (Note the 'converters' option provides similar functionality.)

したがって、セパレータ'::'は正規表現として解釈されます。パンダのドキュメントとしておよそsep言う:

Regular expressions are accepted and will force use of the python parsing engine

(強調鉱山)

したがって、パンダは、データを読み取るために、「Pythonのエンジン」を使用します。次のエラー行では、このようなPythonエンジンの使用により、dtypeは無視されます。 (おそらく、C-エンジンは、DTYPEを使用することができますnumpyのを意味し、Pythonは明らかdtypesに対処しません。)


あなたはどちらかからdtype引数を削除するにはどうすればよい

にそれを解決するためにread_csvに電話をかけても(警告が表示されます)、区切り記号について何かしてください。

2番目のオプションは難しいようです。エスケープまたは生の文字列は役に立ちません。どうやら、1文字以上の区切り記号は、Pandasによって正規表現によって解釈されます。それは物事のパンダの側に残念な決定かもしれません。

このすべてを回避する1つの方法は、単一の':'をセパレータとして使用し、他のすべての(空の)列を避けることです。例えば:(。またはあなたがrangeを使用して設定している場合usecols=range(0, 5, 2)を使用)

ratings = pd.read_csv(filename, sep=':', names=r_cols, 
         usecols=[0, 2, 4], dtype=r_types) 


補遺

OPは正しく単一:文字を持つフィールドについてのポイントを提起します。おそらく、これを回避する方法がありますが、そうでなければ、代わりにnumpyののgenfromtxt使用して、それを2段階のアプローチを行うことができます。データレコードの

# genfromtxt requires a proper numpy dtype, not a dict 
# for Python 3, we need U10 for strings 
dtype = np.dtype([('userId', 'U10'), ('movieID', 'U10'), 
        ('rating', np.float64)]) 
data = np.genfromtxt(filename, dtype=dtype, names=r_cols, 
        delimiter='::', usecols=list(range(3))) 
ratings = pd.DataFrame(data) 
+0

一つは、単一の持っている「:」データフィールド内。したがって、PythonはCエラーを投げつけ続けます。「12行目の5つのフィールドが予想され、6が見える」とにかくこれに対処するには? – Cloud

+0

その時点で、私はおそらくテキストエディタでデータファイルを開き、もし存在するかどうかを確認します。ファイル内の任意のコンマまたはセミコロンを使用し、 ':'の代わりに '、'を使用します。もちろん、私はファイルにアクセスできます。 – Evert

+0

@Cloud Pandasメーリングリストであなたの状況について尋ねることができます( ''::'を正規表現として解釈するのを避ける方法、これをテストしたときにバックスラッシュが機能しない、またはPandas githubで問題を提出するページ。 – Evert

関連する問題