如何同时选择一个数组中所有奇数行和偶数列?

32

我是编程新手,需要一个程序,能够一次性选择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]
我读到了一些关于(: even)的内容,但不知道该如何使用它。谢谢你的帮助。
汉。

2
你能更清楚地说明期望的输出是什么吗? - jterrace
3个回答

92

假设你有这个数组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]])

要获取每隔一行的奇数行,就像你上面提到的:

>>> x[::2]
array([[ 1,  2,  3,  4,  5],
       [11, 12, 13, 14, 15]])

要获取每隔一个偶数列,就像您上面提到的:

>>> x[:, 1::2]
array([[ 2,  4],
       [ 7,  9],
       [12, 14],
       [17, 19]])

然后将它们组合在一起得到:

>>> x[::2, 1::2]
array([[ 2,  4],
       [12, 14]])

要了解更多详情,请查看索引文档页面。


3
由于NumPy数组的索引从零开始,我认为你的建议是获取偶数行和奇数列。 - lebca
3
这看起来像是魔法,所以我研究了文档。为什么这样做有效:NumPy索引遵循start:stop:stride的惯例。https://numpy.org/doc/stable/user/basics.indexing.html?highlight=indexing#other-indexing-options - gprasant
1
@ErnieSender - 请参阅https://numpy.org/doc/stable/user/basics.indexing.html。 - jterrace
@ErnieSender,我的理解是这意味着从索引1开始,步长为2(在这种特定情况下与列有关,因为它在“,”之后),即如果您的列ID为0,1,2,3,4,5等,则会取1,3,5等。 - RAM237

6
获取每个奇数列的另一个奇数列:
 x[:,0::2]

基于start:stop:step语法。改变start可以改变你想要的是奇数还是偶数。 - Apps 247

2

切片数组:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6],[7, 8, 9],[10, 11, 12],[13, 14, 15]])

case1=arr[::2,:]    #odd rows
case2=arr[1::2,:]   #even rows
case3=arr[:,::2]    #odd cols
case4=arr[:,1::2]   #even cols
print(case1)
print("\n") 
print(case2)
print("\n") 
print(case3)
print("\n") 
print(case4)
print("\n")      

提供:

[[ 1  2  3]
 [ 7  8  9]
 [13 14 15]]


[[ 4  5  6]
 [10 11 12]]


[[ 1  3]
 [ 4  6]
 [ 7  9]
 [10 12]
 [13 15]]


[[ 2]
 [ 5]
 [ 8]
 [11]
 [14]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接