python - NumPy:新旧数据描述符的大小不匹配

标签 python csv numpy genfromtxt

我在读取 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/

相关文章:

python - 在 Flask-SQLAlchemy 中,我应该在哪里初始化和存储数据库对象?

python - 为什么感知器学习算法不收敛?

python - Dask:处理 react 迟钝的 worker

python:使用 CSV 阅读器从 tarfile 中提取单个文件

numpy - 将数组的最后一维拆分为低维数组

python - Kafka-python 如何消费json消息

python - 如何使用 python 删除 csv 文件中逗号前后的空格?

csv - 在 Flink 中解析 CSV 时,在引用字段内转义引号

python - 将 2D numpy 数组列表转换为一个 3D numpy 数组?

python - 有没有办法让 numpy 数组中的数字随机为正或负?