我有一个名为data
的3x3数组和一个名为idx
的3x3索引数组。我希望能够使用广播获得一个由data
组成的新数组,该数组由idx
提供的索引组成。我可以天真地处理这个问题,并在一个for-循环中这样做,如下面的示例所示,然后将其与强制执行的expected
数组进行比较:
import numpy as np
data = np.array([[0.5, 1.5, 2.5], [0.5, 1.5, 2.5], [0.5, 1.5, 2.5]])
idx = np.array([[0,-1,-2], [1,0,-1], [2,1,0]])
expected = np.array([[0.5, 2.5, 1.5], [1.5, 0.5, 2.5], [2.5, 1.5, 0.5]])
result = np.zeros(np.shape(data))
for i in range(len(idx)):
for j in range(len(idx[i])):
result[i,j]=data[i, idx[i,j]]
print(expected==result)
# Gives: 3x3 array of True
我之所以把它带到这里来,是因为我需要将它应用于NxM数组,如果像上面的例子那样应用它,这需要很长时间来计算。
我发现了两个类似的问题(one和two),它们与我的问题有关,但我不知道如何将它们应用到任意大的2D数组中。我在没有运气的情况下尝试了以下几点:
result = data[np.ix_(*idx)]
# Gives Error: too many indices for array: array is 2-dimensional, but 3 were indexed
和
for i in range(len(idx)):
sub = np.ix_(idx[i])
print(sub)
# Gives: (array([ 0, -1, -2]),)
result[i] = data[sub]
print(result)
# Gives Error: could not broadcast input array from shape (3,3) into shape (3,)
必须有一种方法来简单地处理Numpy,而我只是还没有找到。
发布于 2022-05-27 19:06:13
如果还显式指定列值,则将得到该行为。
import numpy as np
data = np.array([[0.5, 1.5, 2.5], [0.5, 1.5, 2.5]])
idx = np.array([[0,-1,-2], [1,0,-1]])
expected = np.array([[0.5, 2.5, 1.5], [1.5, 0.5, 2.5]])
print(data[np.arange(len(data)).reshape(-1,1),idx] == expected)
输出:
[[ True True True]
[ True True True]]
https://stackoverflow.com/questions/72409802
复制相似问题