如何在python中将csv文件导入为numpy.array?

时间:2014-09-02 01:45:00

标签: python csv numpy

说我有这种格式的csv file.csv:

dfaefew,432,1
vzcxvvz,300,1
ewrwefd,432,0

如何将第二列作为numpy.array导入,将第三列作为另一个列导入如下:

second = np.array([432, 300, 432])
third = np.array([1, 1, 0])

我在Ubuntu中使用python2.7。

提前!

2 个答案:

答案 0 :(得分:42)

numpy.genfromtxt()是最好的选择

import numpy as np
csv = np.genfromtxt ('file.csv', delimiter=",")
second = csv[:,1]
third = csv[:,2]

>>> second
Out[1]: array([ 432.,  300.,  432.])

>>> third
Out[2]: array([ 1.,  1.,  0.])

答案 1 :(得分:11)

您可以使用numpy.loadtxt

In [15]: !cat data.csv
dfaefew,432,1
vzcxvvz,300,1
ewrwefd,432,0

In [16]: second, third = loadtxt('data.csv', delimiter=',', usecols=(1,2), unpack=True, dtype=int)

In [17]: second
Out[17]: array([432, 300, 432])

In [18]: third
Out[18]: array([1, 1, 0])

numpy.genfromtxt

In [19]: second, third = genfromtxt('data.csv', delimiter=',', usecols=(1,2), unpack=True, dtype=None)

参数的唯一变化是我使用dtype=None,它告诉genfromtxt从文件中找到的值推断数据类型。