我在读取 CSV 文件时遇到了 NumPy 1.10.2 的以下问题。我不知道如何为 genfromtxt
提供显式数据类型。
这是 CSV,minimal.csv
:
x,y
1,hello
2,hello
3,jello
4,jelly
5,belly
这里我尝试用genfromtxt来阅读它:
import numpy
numpy.genfromtxt('minimal.csv', dtype=(int, str))
我也试过:
import numpy
numpy.genfromtxt('minimal.csv', names=True, dtype=(int, str))
无论如何,我得到了错误:
Traceback (most recent call last):
File "visualize_numpy.py", line 39, in <module>
numpy.genfromtxt('minimal.csv', dtype=(int, str))
File "/Users/xeli/workspace/myproj/env/lib/python3.5/site-packages/numpy/lib/npyio.py", line 1518, in genfromtxt
replace_space=replace_space)
File "/Users/xeli/workspace/myproj/env/lib/python3.5/site-packages/numpy/lib/_iotools.py", line 881, in easy_dtype
ndtype = np.dtype(ndtype)
ValueError: mismatch in size of old and new data-descriptor
或者,我试过:
import numpy
numpy.genfromtxt('minimal.csv', dtype=[('x', int), ('y', str)])
抛出:
Traceback (most recent call last):
File "visualize_numpy.py", line 39, in <module>
numpy.genfromtxt('minimal.csv', dtype=[('x', int), ('y', str)])
File "/Users/xeli/workspace/myproj/env/lib/python3.5/site-packages/numpy/lib/npyio.py", line 1834, in genfromtxt
rows = np.array(data, dtype=[('', _) for _ in dtype_flat])
ValueError: size of tuple must match number of fields.
我知道 dtype=None
让 NumPy 尝试猜测正确的类型并且通常运行良好。但是,文档提到它比显式类型慢得多。在我的例子中,计算效率是必需的,所以 dtype=None
不是一个选项。
我的方法或 NumPy 有什么严重错误吗?
最佳答案
这很好用,并保留了您的 header 信息:
df = numpy.genfromtxt('minimal.csv',
names=True,
dtype=None,
delimiter=',')
这使得 genfromtxt
猜测 dtype,这通常是您想要的。分隔符是逗号,所以我们也应该传递该参数,最后,names=True
保留 header 信息。
像使用任何框架一样访问您的数据:
>>>>print(df['x'])
[1 2 3 4 5]
编辑:根据您在下面的评论,您可以明确提供数据类型,如下所示:
df = numpy.genfromtxt('file1.csv',
names=True,
dtype=[('x', int), ('y', 'S5')], # assuming each string is of len =< 5
delimiter=',')
关于python - NumPy:新旧数据描述符的大小不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34294742/