二维数组的numpy loadtxt

时间:2018-12-06 05:01:51

标签: python-3.x numpy deep-learning computer-vision

我正在使用numpy的loadtxt函数加载虹膜数据集,并预期返回的ndarray的形状为(150,5),但是返回的形状为(150,)。显然,loadtxt方法是将2D数组存储为行列表。如何使loadtxt方法以2D数组形式返回数据。请不要在此处建议使用熊猫。

好吧,这是我使用的简单代码段:

import numpy as np


values = np.genfromtxt('iris.txt', delimiter=',',dtype={'names': ('sepal length', 'sepal width', 'petal length', 'petal width', 'label'),
                      'formats': (np.float, np.float, np.float, np.float, 'U15')}, usecols=[0,1,2,3,4])
print(values.shape)

1 个答案:

答案 0 :(得分:1)

查看loadtxt的{​​{1}}文档:

dtype

您的Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type. 是结构化的数据类型:

dtype

dtype={'names': ('sepal length', 'sepal width', 'petal length', 'petal width', 'label'), 'formats': (np.float, np.float, np.float, np.float, 'U15')} 中的5个值匹配的5个字段。

您使用名称索引访问字段,例如usecolsvalues['sepal length']