【问题标题】:How to reorder a numpy array by giving each element a new index?如何通过为每个元素提供新索引来重新排序 numpy 数组?
【发布时间】:2022-12-05 06:11:53
【问题描述】:

我想要重新排序一个 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]

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

【问题讨论】:

  • my_array[new_indiced] 这样做。

标签: python arrays numpy


【解决方案1】:

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

reordered_array = my_array.take(new_indices)

print(reordered_array)  # [98, 31, 23, 0, 54]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多