Reputation: 6759
I have some data array
a = [6,4,3,1,5]
and a "to location array", that gives indices for how these elements should be reshuffled,
b = [4,2,0,1,3]
What this means: the 1st element of a
should go to index 4, the 2nd element of a
should go to index 2, and so on. So when applying b
to a
, I should get:
c = [3,1,4,5,6]
However, I am struggling to implement this operation. Is it a common operation? If so, could someone give me an example? I want to generate some array d
from b
so that
c = a[d]
In the above example,
d = [2,3,1,4,0]
What I tried: d = b[b]
, but this is not always correct.
Upvotes: 0
Views: 49
Reputation: 6759
One method I just found is calculating d
is as follows:
d = np.zeros(5);
d[b] = np.arange(5)
But it seems very non-intuitive to me.
Upvotes: 1
Reputation: 40698
If you don't need d
, you can directly get c
with np.put_along_axis
:
>>> a = np.array([6,4,3,1,5])
>>> b = np.array([4,2,0,1,3])
>>> c = np.zeros_like(b)
>>> np.put_along_axis(c, b, a, 0)
>>> c
array([3, 1, 4, 5, 6])
Note the operation is inplace.
Upvotes: 1