将csv转换为numpy对象

时间:2019-04-29 16:18:48

标签: python numpy

我的CSV文件中包含以下数据:

"sepal_length,sepal_width,petal_length,petal_width,species"
"5.1,3.5,1.4,0.2,setosa"
"4.9,3,1.4,0.2,setosa"
"4.7,3.2,1.3,0.2,setosa"

加载文件以转换为numpy对象:

import numpy as np
loaded_csv = np.genfromtxt('iris.csv', delimiter=',')

输出:

[[nan nan nan nan nan]
[nan 3.5 1.4 0.2 nan]
[nan 3.  1.4 0.2 nan]
[nan 3.2 1.3 0.2 nan]
[nan 3.1 1.5 0.2 nan]]

如何保留字符串文本并使第一个元素视为浮点数?

1 个答案:

答案 0 :(得分:1)

使用正确的dtypenames(标题使用),您可以获得结构化的数组:

In [148]: alist=["sepal_length,sepal_width,petal_length,petal_width,species", 
     ...: "5.1,3.5,1.4,0.2,setosa", 
     ...: "4.9,3,1.4,0.2,setosa", 
     ...: "4.7,3.2,1.3,0.2,setosa"]                                                  

In [150]: data = np.genfromtxt(alist, delimiter=',', dtype=None, names=True, encoding=None)                                                                     
In [151]: data                                                                       
Out[151]: 
array([(5.1, 3.5, 1.4, 0.2, 'setosa'), (4.9, 3. , 1.4, 0.2, 'setosa'),
       (4.7, 3.2, 1.3, 0.2, 'setosa')],
      dtype=[('sepal_length', '<f8'), ('sepal_width', '<f8'), ('petal_length', '<f8'), ('petal_width', '<f8'), ('species', '<U6')])

这是一个名为fields的一维数组:

In [152]: data['sepal_length']                                                       
Out[152]: array([5.1, 4.9, 4.7])
In [153]: data['species']                                                            
Out[153]: array(['setosa', 'setosa', 'setosa'], dtype='<U6')