使用numpy.genfromtxt出现TypeError错误:无法隐式将“bytes”对象转换为“str”。

3

我有一个来自kaggle.com的python项目,遇到了读取数据集的问题。它只有一个csv文件。我们需要将其读入并将目标和训练部分放入数组中。

以下是数据集的前3行(目标列为第19列,特征为前18列):

user    gender  age how_tall_in_meters  weight  body_mass_index x1  
debora  Woman   46  1.62    75  28.6    -3  
debora  Woman   46  1.62    75  28.6    -3  

这里未显示的目标列具有字符串值。
from pandas import read_csv
import numpy as np
from sklearn.linear_model.stochastic_gradient import SGDClassifier
from sklearn import preprocessing
import sklearn.metrics as metrics
from sklearn.cross_validation import train_test_split

#d = pd.read_csv("data.csv", dtype={'A': np.str(), 'B': np.str(), 'S': np.str()})

dataset = np.genfromtxt(open('data.csv','r'), delimiter=',', dtype='f8')[1:]
target = np.array([x[19] for x in dataset])
train = np.array([x[1:] for x in dataset])

print(target)

我收到的错误信息是:
Traceback (most recent call last):
  File "C:\Users\Cameron\Desktop\Project - Machine learning\datafilesforproj\SGD_classifier.py", line 12, in <module>
    dataset = np.genfromtxt(open('data.csv','r'), delimiter=',', dtype='f8')[1:]
  File "C:\Python33\lib\site-packages\numpy\lib\npyio.py", line 1380, in genfromtxt
    first_values = split_line(first_line)
  File "C:\Python33\lib\site-packages\numpy\lib\_iotools.py", line 217, in _delimited_splitter
    line = line.split(self.comments)[0]
TypeError: Can't convert 'bytes' object to str implicitly

请花些时间将代码格式化正确。 - Hooked
此外,请尝试提供一个最小工作示例。你的问题与Kaggle.com无关。你应该尝试将程序缩减到2行以隔离问题。同时,创建一个极其简单的.csv文件进行练习。 - Garrett
@CoDEmanX 不是的。这是针对numpy的特定问题,详见我的回答。 - smheidrich
5个回答

4
我的建议是将这行代码修改为:
dataset = np.genfromtxt(open('data.csv','r'), delimiter=',', dtype='f8')[1:]

to

dataset = np.genfromtxt('data.csv', delimiter=',', dtype='f8')[1:]

很不幸,我不太确定根本问题是什么。


1
完全没有帮助... 与OP相同的文件,"dataset"的内容为:[nan,nan] - andrea

3

实际上这是numpy中的一个bug,参见issue#3184

我只会复制我在那里提出的解决方法:

import functools
import io
import numpy as np
import sys

genfromtxt_old = np.genfromtxt
@functools.wraps(genfromtxt_old)
def genfromtxt_py3_fixed(f, encoding="utf-8", *args, **kwargs):
  if isinstance(f, io.TextIOBase):
    if hasattr(f, "buffer") and hasattr(f.buffer, "raw") and \
    isinstance(f.buffer.raw, io.FileIO):
      # Best case: get underlying FileIO stream (binary!) and use that
      fb = f.buffer.raw
      # Reset cursor on the underlying object to match that on wrapper
      fb.seek(f.tell())
      result = genfromtxt_old(fb, *args, **kwargs)
      # Reset cursor on wrapper to match that of the underlying object
      f.seek(fb.tell())
    else:
      # Not very good but works: Put entire contents into BytesIO object,
      # otherwise same ideas as above
      old_cursor_pos = f.tell()
      fb = io.BytesIO(bytes(f.read(), encoding=encoding))
      result = genfromtxt_old(fb, *args, **kwargs)
      f.seek(old_cursor_pos + fb.tell())
  else:
    result = genfromtxt_old(f, *args, **kwargs)
  return result

if sys.version_info >= (3,):
  np.genfromtxt = genfromtxt_py3_fixed

在代码顶部加入这段代码后,您可以在Python 3中再次使用np.genfromtxt,并且应该能够正常工作。

1

0

你需要显式地将 bytes 对象解码为 str 对象,因为这个 TypeError 暗示了这一点。

# For instance, interpret as UTF-8 (depends on your source)
self.comments = self.comments.decode('utf-8')

3
有问题的代码位于numpy库中。你是在暗示这是一个numpy的bug吗?如果是,请编辑你的回答以澄清这一点。 - max
同意,我正在运行这里的第一个例子,但出现了相同的错误:http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.genfromtxt.html - andrea

-1

不要:

dataset = np.genfromtxt(open('data.csv','r'), delimiter=',', dtype='f8')[1:]

试试这个:

dataset = np.genfromtxt('C:\\\\..\\\\..\\\train.csv', delimiter=',', dtype='None')[1:]

请注意,您必须使用额外的 '\' 来转义其他字符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接