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?
CodePudding user response:
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]