简体   繁体   English

python(numpy):如何从CSV文件读取特定的列?

[英]python(numpy): how to read specific columns from CSV file?

I have a CSV data file, 100 columns * 100,000 lows and one header. 我有一个CSV数据文件,100列* 100,000个低点和一个标头。

First, I want to make a list containing 1st, 3rd, and 5th to 100,000th columns data of original CSV data file. 首先,我要创建一个包含原始CSV数据文件的第1、3、5至100,000列数据的列表。

In that case, I think I can use the script like below. 在这种情况下,我想我可以使用如下脚本。

#Load data
xy = np.loadtxt('CSV data.csv', delimiter=',', skiprows=1)
x = xy[:,[1,3,5,6,7,8,9,10,11 .......,100000]]

But, as you know, it is not good method. 但是,正如您所知,这不是一个好方法。 It is difficult to type and it is not good for generalization. 很难键入,也不能一概而论。

First, I thought the below script could be used but, failed. 首先,我认为可以使用以下脚本,但是失败了。

x = xy[:,[1,3,5:100000]]

How can I make a separate list using specific columns data, separated and continuous? 如何使用特定的列数据创建单独的列表,分隔并连续?

Just use the usecols parameter in np.loadtxt() .: 只需在np.loadtxt()使用usecols参数np.loadtxt()

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html

np.r_ is a convenience function (actually an object that takes [] ), that generates an array of indices: np.r_是一个便利函数(实际上是一个带有[]的对象),它生成一个索引数组:

In [76]: np.r_[1,3,5:100]
Out[76]: 
array([ 1,  3,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
       20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
       37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
       54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
       71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
       88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

This should be usable for both xy[:,np.r_[...]] and the usecols parameter. 这对于xy[:,np.r_[...]]usecols参数usecols

In [78]: np.arange(300).reshape(3,100)[:,np.r_[1,3,5:100:10]]
Out[78]: 
array([[  1,   3,   5,  15,  25,  35,  45,  55,  65,  75,  85,  95],
       [101, 103, 105, 115, 125, 135, 145, 155, 165, 175, 185, 195],
       [201, 203, 205, 215, 225, 235, 245, 255, 265, 275, 285, 295]])

另一种选择是通过从xy删除列来定义x

x = np.delete(xy, [0,2,4], axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM