[英]How to slice a np.array using a list of unknown length?
I am probably using the wrong names/notation (and an answer probably exists on SO, but I can't find it).
我可能使用了错误的名称/符号(并且答案可能存在于SO上,但我找不到它)。 Please help me clarify so that I can update the post, and help people like me in the future.
请帮助我澄清一下,以便我可以更新帖子,并在以后帮助像我这样的人。
I have an array A
of unknown dimension n
, and a list of indexes of unknown length l
, where l<=n
. 我有一个未知维
n
的数组A
和一个未知长度l
的索引列表,其中l<=n
。
I want to be able to select the slice of A
that correspond to the indexes in l
. 我希望能够选择与
l
的索引相对应的A
的切片。 Ie I want: 即我要:
A = np.zeros([3,4,5])
idx = [1,3]
B = # general command I am looking for
B_bad = A[idx] # shape = (2,4,5), not what I want!
B_manual = A[idx[0], idx[1]] # shape = (5), what I want, but as a general expression.
# it is okay that the indexes are in order i.e. 0, 1, 2, ...
You need a tuple: 您需要一个元组:
>>> A[tuple(idx)]
array([0., 0., 0., 0., 0.])
>>> A[tuple(idx)].shape
(5,)
Indexing with a list
doesn't have the same meaning. 用
list
索引的含义不同。 See numpy
's documentation on indexing for more information. 有关更多信息,请参见
numpy
有关索引的文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.