python - 使用 numpy 对数组进行排序

标签 python sorting numpy lexicographic

我想更改

中列元素的顺序
a = np.asarray(
[[0,1,1,2,2,2,2,3,3,3,4,4,4,4,4,4],
 [4,0,3,0,1,2,5,1,2,5,3,4,6,6,7,7],
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,1,0,0,0,1,1,0,1,0,1]]
)

基于第 1-3 行的值(从 0 开始)。我的解决方案目前如下所示:

a[:, a.transpose()[:, 1].argsort(axis=0)]

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

这很好,除了我还想在搜索中包含第 2-3 行(按字典顺序)。理想情况下,我期望最后一行是 [0, 1, 0, 1, ..., 0, 1] 的结果(充满零的第二行也应该考虑在内)帐户,但在本例中它包含相同的值)。

最佳答案

您需要numpy.lexsort ,相当于 argsort ,但基于多个排序键;给定多个数组,它返回索引以按顺序对数组进行排序:

Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, it’s rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.

a[:, np.lexsort(a[:0:-1])]
#array([[2, 1, 3, 2, 3, 2, 1, 4, 0, 4, 3, 2, 4, 4, 4, 4],
#       [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7],
#       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#       [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]])

关于python - 使用 numpy 对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811792/

相关文章:

python - 在 Python/Numpy 中一次分配相同的数组索引

python - 如何使用一个git克隆项目作为另一个git项目的导入库

python - 如何在 Azure ML Studio 中保存 ipython 笔记本中的数据集?

python - OpenCV 硬币检测和自动结果检查

python - 在不导入任何模块的情况下以 min :sec, 格式对时间进行排序的有效方法是什么?

python - 对逗号分隔的数字字符串进行数字排序

python - 从多索引 pandas 数据框中引用 pandas 系列值

python - 安装 basemap 时出现 UnsatisfiableError

c# - 按自定义顺序排序

python - 实践中的最小二乘法