在numpy数组中获取每行特定列
可能重复的问题:
numpy:按列访问数组
我有一个numpy数组(numpy被导入为np)
gona = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
我可以通过gona[1][:]来获取第1行的整个列的值。
array([4, 5, 6])
但是如果我想获取所有行中特定列的所有值(比如我想要每一行的第1列的值),我会尝试gona[:][1]。但我得到的结果和之前是一样的。
这可能是什么原因呢?我该如何在numpy中做到这一点呢?
3 个回答
0
像这样:
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
输出结果:
>>>
[1, 4, 7, 10]
>>>
8
在大括号的位置上似乎有一点小混淆,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])
你也可以选择一系列的行,比如说:
gona[0:2,0] # only take the two first rows of the first column
Out[24]: array([2, 5])