Python - Numpy:我如何同时选择数组的所有奇数行和所有偶数列

use*_*701 20 python numpy

我是编程新手,我需要一个程序,可以在一个代码中同时选择Numpy数组的所有奇数行和所有偶数列.这是我试过的:

>In [78]: a

>Out[78]:
>array([[ 1,  2,  3,  4,  5],
>       [ 6,  7,  8,  9, 10],
>       [11, 12, 13, 14, 15],
>       [16, 17, 18, 19, 20]])
>
>In [79]: for value in range(a.shape[0]):
>     if value %2 == 0:
>        print a[value,:]

>[1 2 3 4 5]
>[11 12 13 14 15]
>
>In [82]: for value in range(a.shape[1]):
>    if value %2 == 1:
>        print a[:,value]

>[ 2  7 12 17]
>[ 4  9 14 19]
Run Code Online (Sandbox Code Playgroud)

我读过"(:偶数)"的东西,但不知道我能用它.谢谢你的帮助.

jte*_*ace 57

假设你有这个数组,x:

>>> import numpy
>>> x = numpy.array([[ 1,  2,  3,  4,  5],
... [ 6,  7,  8,  9, 10],
... [11, 12, 13, 14, 15],
... [16, 17, 18, 19, 20]])
Run Code Online (Sandbox Code Playgroud)

要获得其他所有奇数行,就像上面提到的那样:

>>> x[::2]
array([[ 1,  2,  3,  4,  5],
       [11, 12, 13, 14, 15]])
Run Code Online (Sandbox Code Playgroud)

为了得到所有其他偶数列,如上所述:

>>> x[:, 1::2]
array([[ 2,  4],
       [ 7,  9],
       [12, 14],
       [17, 19]])
Run Code Online (Sandbox Code Playgroud)

然后,将它们组合在一起产生:

>>> x[::2, 1::2]
array([[ 2,  4],
       [12, 14]])
Run Code Online (Sandbox Code Playgroud)

  • 由于 numpy 数组的索引为零,我相信您建议获取偶数行和奇数列。 (3认同)
  • 这看起来很神奇,所以我深入研究了文档。为什么这样有效:Numpy 索引遵循 start:stop:stride 约定。https://numpy.org/doc/stable/user/basics.indexing.html?highlight=indexing#other-indexing-options (3认同)

小智 5

要获取每隔一个奇数列:

 x[:,0::2]
Run Code Online (Sandbox Code Playgroud)