在多个维度numpy的花哨索引 [英] Numpy fancy indexing in multiple dimensions
问题描述
让我们说我有大小为n×m的值X k的numpy的数组A并具有指数从1到K的大小为n×m的另一列B上。
我要访问使用在这个地方B中给出的指数每个n×m的切片,
给我的大小为n×m的数组。
Let's say I have an numpy array A of size n x m x k and another array B of size n x m that has indices from 1 to k. I want to access each n x m slice of A using the index given at this place in B, giving me an array of size n x m.
编辑:这显然不是我想要的!
[我可以通过实现这个取
是这样的:
that is apparently not what I want!
[[ I can achieve this using take
like this:
A.take(B)
]]年底修改
可以这样使用花哨的索引实现?
我还以为 A [B]
将给予相同的结果,但结果
在大小的N×米×米×k的数组(我真的不明白)。
Can this be achieved using fancy indexing?
I would have thought A[B]
would give the same result, but that results
in an array of size n x m x m x k (which I don't really understand).
我不希望使用的原因取
是我希望能够在这部分上指定的东西,像
The reason I don't want to use take
is that I want to be able to assign this portion something, like
A [B] = 1
这是我到目前为止的唯一可行的解决方案是
The only working solution that I have so far is
A.reshape(-1,K)[np.arange(N * M),B.ravel()]。重塑(N,M)
但肯定必须有一个更简单的方法?
but surely there has to be an easier way?
推荐答案
假设
import numpy as np
np.random.seed(0)
n,m,k = 2,3,5
A = np.arange(n*m*k,0,-1).reshape((n,m,k))
print(A)
# [[[30 29 28 27 26]
# [25 24 23 22 21]
# [20 19 18 17 16]]
# [[15 14 13 12 11]
# [10 9 8 7 6]
# [ 5 4 3 2 1]]]
B = np.random.randint(k, size=(n,m))
print(B)
# [[4 0 3]
# [3 3 1]]
要创建这个数组,
print(A.reshape(-1, k)[np.arange(n * m), B.ravel()])
# [26 25 17 12 7 4]
由于使用花哨的索引一个 n×m个
数组:
i,j = np.ogrid[0:n, 0:m]
print(A[i, j, B])
# [[26 25 17]
# [12 7 4]]
这篇关于在多个维度numpy的花哨索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!