How to reorder a numpy array by giving each element a new index?

Question:

I want to reorder a numpy array, such that each element is given a new index.

# I want my_array's elements to use new_indicies's indexes.
my_array = np.array([23, 54, 67, 98, 31])
new_indicies = [2, 4, 1, 0, 1]

# Some magic using new_indicies at my_array

# Note that I earlier gave 67 and 31 the index 1 and since 31 is last, that is the one i'm keeping.
>>> [98, 31, 23, 0, 54]

What would be an efficient approach to this problem?

Asked By: Magnus Enebakk

||

Answers:

To reorder the elements in a NumPy array according to a set of new indices, you can use the put() method.

# Create an empty array of zeros with the same size as my_array
reordered_array = np.zeros_like(my_array)

# Move the elements in my_array to the indices specified in new_indices
reordered_array.put(new_indices, my_array)

print(reordered_array)  # [98, 31, 23, 0, 54]
Answered By: mxwmnn
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.