简体   繁体   English

Python 使用索引元组切片 numpy 数组

[英]Python slicing numpy array with index tuple

I want to slice an N-dimensional numpy array a using an N-1-dimensional index tuple b .我想使用 N-1 维索引元组b对 N 维 numpy 数组a进行切片。 Below is a case with N = 4:下面是 N = 4 的情况:

import numpy as np

a = np.random.rand(20,1,5,4)
b1 = (0,0,0)
b2 = (0,3,2)

# want to get the slice c = a[:,b2[0],b2[1],b2[2]] without explicitly writing all N-1 elements of b2

c = a[:,b1] # no error message, but gives a[:,[b1[0],b1[1],b1[2]],:,:]
c = a[:,b2] # error message (because b2[1] = 3 larger than a.shape[1])

What is the correct way to "unpack" the tuple index elements into the different dimensions?将元组索引元素“解包”到不同维度的正确方法是什么? I tried using the asterisk operator ( *b ), but that did not seem to work.我尝试使用星号运算符 ( *b ),但这似乎不起作用。

a[(..., *b1)]

This boils down to calling the __getitem__ method manually with a variable argument in the index tuple:这归结为使用索引元组中的变量参数手动调用__getitem__方法:

In [23]: a.__getitem__((..., *b1))
Out[23]: 
array([0.93049554, 0.63858628, 0.31665933, 0.15048072, 0.17083849,
       0.34621308, 0.66980288, 0.75191251, 0.05844084, 0.16715787,
       0.80409005, 0.64181912, 0.76463963, 0.75616746, 0.44955961,
       0.19034925, 0.8841084 , 0.54450091, 0.02033021, 0.21275405])

In [21]: a[:, 0, 0, 0]
Out[21]: 
array([0.93049554, 0.63858628, 0.31665933, 0.15048072, 0.17083849,
       0.34621308, 0.66980288, 0.75191251, 0.05844084, 0.16715787,
       0.80409005, 0.64181912, 0.76463963, 0.75616746, 0.44955961,
       0.19034925, 0.8841084 , 0.54450091, 0.02033021, 0.21275405])

Be aware though that the usage of the ellipsis ( ... ) has a slightly more general meaning.请注意,省略号 ( ... ) 的使用具有更一般的含义。 Otherwise, you have to construct the : slice manually:否则,您必须手动构造:切片:

In [20]: a.__getitem__((slice(None), *b1))
Out[20]: 
array([0.93049554, 0.63858628, 0.31665933, 0.15048072, 0.17083849,
       0.34621308, 0.66980288, 0.75191251, 0.05844084, 0.16715787,
       0.80409005, 0.64181912, 0.76463963, 0.75616746, 0.44955961,
       0.19034925, 0.8841084 , 0.54450091, 0.02033021, 0.21275405])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM