python – 如何访问NumPy多维数组的第i列?

How to access the ith column of a NumPy multidimensional array?

假设我有:

1
test = numpy.array([[1, 2], [3, 4], [5, 6]])

test[i]得到数组的第一线(如[1, 2])。如何访问第i列?(如[1, 3, 5])。另外,这是一个昂贵的手术吗?


字母名称(P)Similarly,(p)字母名称(P)Lets you access rows.This is covered in section 1.4(indexing)of the nupy reference.This is quick,at least in my experience.It's certainly much quicker than accessing each element in a loop.(p)


(P)And if you want to access more than one column at a time you could do:(p)字母名称


字母名称(P)This command gives you a row vector,if you just want to loop over it,it's fine,but if you want to hstack with some other array with dimension 3xn,you will have(p)(P)Valuemisor:all the input arrays must have same number of dimensions(p)(P)鞭子(p)字母名称(P)给你一个秋千向量,所以你可以联系或HSTACK操作。(p)(P)E.G.(p)字母名称


(P)You could also transport and return to row:(p)字母名称


(P)尽管问题已经问过了,让我撒个谎吧。(p)(P)Let's say you are interested in the first column of the Array(p)字母名称(P)As you already known from other answers,to get it in the form of"row vector"(Array of Shape EDOCX1 nipal),you use slicing:(p)字母名称(P)To check if an array is a view or a copy of another array you can do the following:(p)字母名称(P)See Ndray.base.(p)(P)Besides the obvious difference between the two(modifying EDOCX1 original 1 will affect EDOCX1 original 2),the number of byte-steps for traversing each of them is different:(p)字母名称(P)See strides.为什么这么重要?想象一下,你有一个非常大的恒星以东X1音标3(p)字母名称(P)and you want to compute the sum of all the elements of the first column,I.E.EDOCX1 penal 5 or EDOCX1.使用复写版太快了:(p)字母名称(P)This is due to the different number of strides mentioned before:(p)字母名称(P)Although it might seem that using column copies is better,it is not always true for the reason that making a copy takes time and uses more memory(in this case it took me approx.200μs to create the EDOCX1 silios).然而,如果我们需要在第一个地方的预算,或者我们需要在一个具体的结转框架内开展大量不同的业务,我们就可以为Speed作出牺牲性的备忘录,那么,他们做一个预算就是去做的事情。(p)(P)In the case that we are interested in working mostly with columns,it could be a good idea to create our array in column-major(` F')order instead of the row-major(` C')order(which is the default),and they do the slicing as before to get a column without copying it:(p)字母名称(P)Now,performing the sum operation(or any other)on a column-view is much faster.(p)(P)最后,让我注意到,移植一个阵列和使用Row-Slicing是同一个利用哥伦布-Slicing on the original array,because transposing is done by just swapping the shape and the strides of the original array.(p)字母名称


(P)To get several and indepent columns,just:(p)字母名称(P)你会得到秋千0和2(p)


字母名称(P)Then you can select the 2nd-4th column this way:(p)字母名称