Numpy 使用一个数组作为另一个数组的掩码

问题描述 投票:0回答:1

我正在尝试在 NumPy 中执行这些步骤。使用 python list

sort()
argsort()
可以轻松做到这一点。

如何在 Numpy 中执行此操作?

a = np.array([10,30,20,40,50])

a_sorted = np.array([10,20,30,40,50])

获取a_sorted的掩码

b = np.array([one,three,two,four,five])

将面膜敷在b

预期数组根据a_sorted排序:

b_sorted = np.array([one,two,three,four,five])
python arrays numpy sorting mask
1个回答
0
投票

当然!答案如下:


import numpy as np

# Given arrays
a = np.array([10, 30, 20, 40, 50])
b = np.array([1, 3, 2, 4, 5])

# Sort 'a' and retrieve the indices that would sort 'a'
a_sorted_indices = np.argsort(a)

# Use the sorted indices to sort 'a' and 'b'
a_sorted = a[a_sorted_indices]
b_sorted = b[a_sorted_indices]

print("Sorted 'a':", a_sorted)  # Output: [10 20 30 40 50]
print("Sorted 'b' according to 'a':", b_sorted)  # Output: [1 2 3 4 5]

说明:

  1. np.argsort(a)
    返回对数组进行排序的索引
    a
  2. a_sorted_indices
    保存用于排序的索引
    a
  3. a[a_sorted_indices]
    使用排序索引检索
    a
    的元素,给出
    a_sorted
  4. b[a_sorted_indices]
    使用相同的排序索引来重新排列
    b
    的元素,以对应于
    a
    的排序顺序,从而得到
    b_sorted

此代码对数组“a”进行排序,并根据“a”的顺序对数组“b”进行相同的排序,分别生成

a_sorted
b_sorted

© www.soinside.com 2019 - 2024. All rights reserved.