如何在python中将csv文件导入为numpy.array?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25614749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import csv file as numpy.array in python?
提问by user3692521
say i have a csv file.csv in this format:
说我有一个这种格式的 csv file.csv:
dfaefew,432,1
vzcxvvz,300,1
ewrwefd,432,0
how to import the second column as a numpy.array and the third column as another one like this:
如何将第二列作为 numpy.array 导入,将第三列作为另一列导入,如下所示:
second = np.array([432, 300, 432])
third = np.array([1, 1, 0])
I am using python2.7 in Ubuntu.
我在 Ubuntu 中使用 python2.7。
Thx ahead!
谢谢!
采纳答案by Anoop
numpy.genfromtxt()is the best thing to use here
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.])
回答by Warren Weckesser
You can use numpy.loadtxt:
您可以使用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])
In [19]: second, third = genfromtxt('data.csv', delimiter=',', usecols=(1,2), unpack=True, dtype=None)
The only change in the arguments is that I used dtype=None, which tells genfromtxtto infer the data type from the values that it finds in the file.
参数中唯一的变化是我使用了dtype=None,它告诉genfromtxt从它在文件中找到的值推断数据类型。

