python - 如何从数据文件中导入一个 numpy 结构化数组
问题描述
我正在尝试创建一个数组,其中包含从数据文件导入的 5 列。其中 4 个是浮点数和最后一个字符串。
数据文件如下所示:
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5.0,3.4,1.5,0.2,Iris-setosa
我试过这些:
data = np.genfromtxt(filename, dtype = "float,float,float,float,str", delimiter = ",")
data = np.loadtxt(filename, dtype = "float,float,float,float,str", delimiter = ",")
,但两个代码都只导入第一列。
为什么?我怎样才能解决这个问题?
你的时间!:)
解决方案
您必须正确指定str
类型:"U20"
例如最多 20 个字符:
data = np.loadtxt('data.txt', dtype = "float,"*4 + "U20", delimiter = ",")
似乎工作:
array([( 5.1, 3.5, 1.4, 0.2, 'Iris-setosa'),
( 4.9, 3. , 1.4, 0.2, 'Iris-setosa'),
( 4.7, 3.2, 1.3, 0.2, 'Iris-setosa'),
( 4.6, 3.1, 1.5, 0.2, 'Iris-setosa'),
( 5. , 3.6, 1.4, 0.2, 'Iris-setosa'),
( 5.4, 3.9, 1.7, 0.4, 'Iris-setosa'),
( 4.6, 3.4, 1.4, 0.3, 'Iris-setosa'),
( 5. , 3.4, 1.5, 0.2, 'Iris-setosa')],
dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<U20')])
使用 pandas 的另一种方法为您提供了一个对象数组,但这会减慢进一步的计算:
In [336]: pd.read_csv('data.txt',header=None).values
Out[336]:
array([[5.1, 3.5, 1.4, 0.2, 'Iris-setosa'],
[4.9, 3.0, 1.4, 0.2, 'Iris-setosa'],
[4.7, 3.2, 1.3, 0.2, 'Iris-setosa'],
[4.6, 3.1, 1.5, 0.2, 'Iris-setosa'],
[5.0, 3.6, 1.4, 0.2, 'Iris-setosa'],
[5.4, 3.9, 1.7, 0.4, 'Iris-setosa'],
[4.6, 3.4, 1.4, 0.3, 'Iris-setosa'],
[5.0, 3.4, 1.5, 0.2, 'Iris-setosa']], dtype=object)
推荐阅读
- assembly - 在 x64 中调用绝对地址
- mysql - 从“where”条件自动生成 MYSQL 列
- python - 在python中使用变量创建一个txt文件
- php - SUT parent 使用 get_class 检查依赖项
- google-places-api - Google Places API - 我可以分离出输出吗?
- csv - 如何从csv文件读取数据并保存到数据库以及spring boot中的多对多关系
- java - Apache 客户端 http/1.1 406 不可接受 Java
- bash - 如何从 curl 资源添加别名
- sccm - Gsview 6.0 创建 SCCM 包的选项
- go - 使用 Go 的 time.Format 时转义数字