Python 仅获取numpy数组中每一行中的特定列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14650584/
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
Getting only particular columns in every row in a numpy array
提问by maheshakya
Possible Duplicate:
numpy: access an array by column
可能的重复:
numpy:按列访问数组
I have a numpy array (numpy is imported as np)
我有一个 numpy 数组(numpy 是作为 np 导入的)
gona = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
I can get the values of entire column of 1th row by gona[1][:].
我可以通过 gona[1][:] 获取第 1 行整列的值。
array([4, 5, 6])
数组([4, 5, 6])
But if I try to get all values of a particular column of all rows (say I want values of 1st column in every row) I would try the gona[:][1]. But the result I get from this is same as before.
但是,如果我尝试获取所有行的特定列的所有值(假设我想要每一行中第一列的值),我会尝试使用 gona[:][1]。但是我从中得到的结果和以前一样。
What can be the reason for this? How do I do such a thing in numpy?
这可能是什么原因?我如何在 numpy 中做这样的事情?
采纳答案by John Vinyard
You actually want to do this:
你实际上想要这样做:
>>> a
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
>>> a[:,1]
array([ 2, 5, 8, 11])
a[:]just returns the entire array, so then a[:][1]is returning the second row of a. I think that's where your confusion arises.
a[:]只返回整个数组,然后a[:][1]返回a. 我想这就是你的困惑出现的地方。
See thissection of the Tentative Numpy Tutorialfor more information on indexing multidimensional arrays.
有关索引多维数组的更多信息,请参阅暂定 Numpy 教程的这一部分。
回答by ATOzTOA
Like this:
像这样:
gona = numpy.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
# List comprehension, just get each element in 'gona', and then get first element in that list
out = [x[0] for x in gona]
print out
Output:
输出:
>>>
[1, 4, 7, 10]
>>>
回答by Matti Lyra
There seems to be a slight confusion in terms of the positioning of the braces, gona[:][1]first selects everything from the array, and from that array then selects the second row. To select particular columns you put the indices within the same square brackets separated by a comma:
大括号的位置似乎有点混乱,gona[:][1]首先从数组中选择所有内容,然后从该数组中选择第二行。要选择特定列,请将索引放在相同的方括号内,以逗号分隔:
gona = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
gona[1,:]
Out[21]: array([4, 5, 6])
gona[:,1]
Out[22]: array([ 2, 5, 8, 11])
gona[:,0]
Out[23]: array([ 1, 4, 7, 10])
you can also just select a range of rows for instance
例如,您也可以只选择一系列行
gona[0:2,0] # only take the two first rows of the first column
Out[24]: array([2, 5])

