【发布时间】:2012-10-03 12:59:00
【问题描述】:
当我尝试使用 genfromtxt 读取以空格分隔的文件并使用转换器函数转换以逗号作为小数分隔符的数字时,出现类型错误。我的转换器功能似乎有问题。但是,当我在单个值上使用它时,它确实可以正常工作。
这是我的代码(我正在使用 Matplotlib/Pylab):
t = dtype([('Date', 'U12'), ('Time', 'U10'), ('Cond', 'f4'), ('Temp', 'f4')])
conv = lambda valstr: float(valstr.replace(',','.'))
c = {2:conv, 3:conv}
data = genfromtxt('Example.csv', dtype = t,
skip_header=1, delimiter = ' ', converters = c)
数据如下:
Date Time Cond Temp
11-10-2012 00:00:14 5,430583 29,5107
11-10-2012 00:00:15 5,431812 29,45066
11-10-2012 00:00:16 5,435501 29,43862
11-10-2012 00:00:17 5,436732 29,43862
...
这是错误信息的一部分:
TypeError Traceback (most recent call last)
<ipython-input-41-c65c2d17c55d> in <module>()
5 c = {2:conv, 3:conv}
6
----> 7 data = genfromtxt('Example.csv', dtype = t, skip_header=1, delimiter = ' ', converters = c)
...
<ipython-input-41-c65c2d17c55d> in <lambda>(valstr)
1 t = dtype([('Date', 'U12'), ('Time', 'U10'), ('Cond', 'f4'), ('Temp', 'f4')])
2
----> 3 conv = lambda valstr: float(valstr.replace(',','.'))
4
5 c = {2:conv, 3:conv}
TypeError: expected an object with the buffer interface
我在这里做错了什么,或者这是 genfromtxt 中的某种错误?
我在 Win7 x64 上使用 Python 3.2。 Numpy 版本是 1.6.2。
【问题讨论】:
-
FWIW,您的代码在 Ubuntu 12.04(64 位)中的 Python 2.7.3 上运行良好。
-
在谷歌搜索了一下之后,当 unicode 字符串函数应用于字节字符串时,似乎会发生这种特定类型的错误。一个小测试证实了这一点: b'test'.replace('t','r') 给出了完全相同的错误。似乎是 Py3 转换问题,这可能就是我的代码在您的 Py2 配置上工作的原因。
标签: python numpy python-3.x matplotlib genfromtxt