我有一个例子,我有如下输入数组
array([[[ 1., 0., 2., 0., 3., 0., 4., 0., 5.],
[ 6., 0., 7., 0., 8., 0., 9., 0., 10.],
[11., 0., 12., 0., 13., 0., 14., 0., 15.]],
[[16., 0., 17., 0., 18., 0., 19., 0., 20.],
[21., 0., 22., 0., 23., 0., 24., 0., 25.],
[26., 0., 27., 0., 28., 0., 29., 0., 30.]]])
我想得到如下所示的输出。
array([[[ 1., 0., 3., 0., 5.],
[ 6., 0., 8., 0., 10.],
[11., 0., 13., 0., 15.]],
[[16., 0., 18., 0., 20.],
[21., 0., 23., 0., 25.],
[26., 0., 28., 0., 30.]]])
如果解决方案能够通用而不仅仅是这个示例,我会很高兴。
最佳答案
由于不能保证最后一个维度的长度是偶数,这里我选择构建bool索引:
>>> mask = np.arange(ar.shape[-1]) // 2 % 2 == 0 # np.arange() & 2 == 0 is faster
>>> mask
array([ True, True, False, False, True, True, False, False, True])
>>> ar[:, :, mask] # or ar[..., mask]
array([[[ 1., 0., 3., 0., 5.],
[ 6., 0., 8., 0., 10.],
[11., 0., 13., 0., 15.]],
[[16., 0., 18., 0., 20.],
[21., 0., 23., 0., 25.],
[26., 0., 28., 0., 30.]]])
如果可以保证最后一个维度的长度均匀,则使用切片 reshape 是另一种技术:
>>> ar
array([[[ 1., 0., 2., 0., 3., 0., 4., 0.],
[ 6., 0., 7., 0., 8., 0., 9., 0.],
[11., 0., 12., 0., 13., 0., 14., 0.]],
[[16., 0., 17., 0., 18., 0., 19., 0.],
[21., 0., 22., 0., 23., 0., 24., 0.],
[26., 0., 27., 0., 28., 0., 29., 0.]]])
>>> shape = ar.shape[:-1]
>>> ar.reshape(*shape, -1, 2)[..., ::2, :].reshape(*shape, -1)
array([[[ 1., 0., 3., 0.],
[ 6., 0., 8., 0.],
[11., 0., 13., 0.]],
[[16., 0., 18., 0.],
[21., 0., 23., 0.],
[26., 0., 28., 0.]]])
关于Python数组: Take two and skip two,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73951659/