python - 根据索引矩阵对 numpy 矩阵进行排序

标签 python arrays numpy sorting matrix

在 numpy 中,我们可以这样对数组进行排序:

>>> import numpy as np

>>> a = np.array([0, 100, 200])
>>> order = np.array([1, 2, 0])
>>> print(a[order])
[100 200   0]

但是,当“顺序”是矩阵时,这不起作用:

>>> A = np.array([    [0, 1, 2],
                      [3, 4, 5],
                      [6, 7, 8]])

>>> Ord = np.array([  [1, 0, 2],
                      [0, 2, 1],
                      [2, 1, 0]])

>>> print(A[Ord].shape)
(3, 3, 3)

我想像这样对“A”进行排序:

array([[1, 0, 2],
       [3, 5, 4],
       [8, 7, 6]])

最佳答案

你可以使用 np.take_along_axis为此。

np.take_along_axis(A, Ord, axis=1)

输出

array([[1, 0, 2],
       [3, 5, 4],
       [8, 7, 6]])

如文档中所述,它通常与生成索引的函数一起使用,例如 argsort。但我不确定这是否会推广到超过 2 个维度。

关于python - 根据索引矩阵对 numpy 矩阵进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66917076/

相关文章:

python - 如何将同一列中至少共享一个 "1"的所有标签(索引)分组?

python - 使用 numpy 计算投影和重构误差的函数 - python

Python:比较两个数组的所有元素并修改第二个数组

arrays - 递归展平多维数组

python - 转换为 numpy 数组会导致 RAM 崩溃

python - 如何在 wxPython 中使用 StaticBox 创建方形 LED 形状

python - OpenAI GPT-3 API 错误 : "AttributeError: module ' openai' has no attribute 'GPT' "

python - 无法连接到主机 api.telegram.org :443 ssl:default

c - 使用 isdigit() 和 isalpha() 命令的最简单方法是什么?

Python - 如何实现与 NumPy 函数兼容的自定义类?