numpy.array select d维数组中的所有偶数元素

numpy.array select all even elements from d-dimensional array

是否有一种高效的 p​​ythonic 方法 select,从 d 维数组中,所有具有偶数索引的元素,而事先不知道 d?以及所有剩余的(即所有至少具有奇数索引的那些)?

第一个问题的最小例子

import numpy as np
a = np.array(range(27)).reshape((3,3,3))
a[::2,::2,::2] 
# -> array([[[ 0,  2],
#            [ 6,  8]],
#           [[18, 20],
#            [24, 26]]])

我为 d 维对象找到的唯一非 pythonic 方式,d 是可变的 至少对于 "all even" 部分,"at least one odd" 仍然逃脱了我。

d = 3
a = np.array(range(3**d)).reshape([3]*d)
b = a
for i in range(d):
    b = np.take(b, np.array(range(0,b.shape[i],2)), axis=i)

我问这个问题的原因(可能已经有更高级别的解决方案)是我想在 n 步中迭代创建一个大小为 (2**n+1, ..., 2**n+1) 的大型 d 维对象,在每个步骤复制前面步骤中的偶数索引元素,例如:

for n in range(N):
    new_array = np.zeros([2**n+1]*d)
    new_array[all_even] = old_array
    new_array[at_least_one_odd] = #something else

提前感谢任何提示!

这是一种使用 np.ix_ -

的方法
a[np.ix_(*[range(0,i,2) for i in a.shape])]

样品运行 -

In [813]: def even_idx(a):
     ...:     return a[np.ix_(*[range(0,i,2) for i in a.shape])]
     ...: 

In [814]: a = np.array(range(27)).reshape((3,3,3))

In [815]: np.allclose(a[::2,::2,::2], even_idx(a) )
Out[815]: True

In [816]: a = np.array(range(27*4)).reshape((3,3,3,4))

In [817]: np.allclose(a[::2,::2,::2,::2], even_idx(a) )
Out[817]: True

In [818]: a = np.array(range(27*4*5)).reshape((3,3,3,4,5))

In [819]: np.allclose(a[::2,::2,::2,::2,::2], even_idx(a) )
Out[819]: True

我猜你可以使用切片对象。

even = a[[slice(None, None, 2) for _ in range(a.ndim)]]
odd = a[[slice(1, None, 2) for _ in range(a.ndim)]]