如何通过给每个元素一个新的索引来重新排序numpy数组?

9lowa7mx  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(115)

我想重新排序一个numpy数组,这样每个元素都有一个新的索引

# 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]

解决这个问题的有效方法是什么?

0lvr5msh

0lvr5msh1#

要根据一组新索引对NumPy数组中的元素重新排序,可以使用put()方法。

# 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]

相关问题