当我读取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有什么严重的问题吗?