[英]Read csv data by numpy
For example, I have csv
file contains ten columns. 例如,我的
csv
文件包含十列。 Is it possible to read it into two variables -- first one will contain 1-2..9 columns and second will contain last column by means of loadtxt
or genfromtxt
? 是否可以将其读取为两个变量-第一个变量将通过
loadtxt
或genfromtxt
包含1-2..9列,第二个变量将包含最后一列?
a = numpy.loadtxt('blah.csv', delimiter=',') # loads it all into one big array
a1 = a[:, :-1] # a view of all but the last column
a2 = a[:, [-1]] # a copy of just the last column
(Or, if you want your last-column variable to be one-dimensional, you can get a view of it using a[:,-1]
instead of saying a[:, [-1]]
.) (或者,如果您希望最后一列变量是一维的,则可以使用
a[:,-1]
而不是说a[:, [-1]]
来查看该视图。)
numpy.loadtext('filename.csv', usecols(0,1,2,...,n-2))
numpy.loadtext('filename.csv', usecols = n-1)
Note: The index of your columns should be decremented by 1, as numpy would start at 0 when loading. 注意:列的索引应减少1,因为numpy在加载时将从0开始。
From the Documentation https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html : 从文档https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html :
usecols : int or sequence, optional Which columns to read, with 0 being the first.
usecols:int或sequence,可选要读取的列,第一列为0。 For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns.
例如,usecols =(1,4,5)将提取第二,第五和第六列。 The default, None, >results in all columns being read."
默认值,无,将导致所有列被读取。”
In case you don't really need numpy. 如果您真的不需要numpy。 You could use pandas ( http://pandas.pydata.org/ ), or csv ( https://docs.python.org/2/library/csv.html ) libraries.
您可以使用pandas( http://pandas.pydata.org/ )或csv( https://docs.python.org/2/library/csv.html )库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.