按列对 NumPy 中的数组进行排序 [英] Sorting arrays in NumPy by column

查看:31
本文介绍了按列对 NumPy 中的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按第 n 列对 NumPy 中的数组进行排序?

How can I sort an array in NumPy by the nth column?

例如

a = array([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5]])

我想按第二列对行进行排序,以便返回:

I'd like to sort rows by the second column, such that I get back:

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

推荐答案

@steveanswer 实际上是最优雅的方法.

@steve's answer is actually the most elegant way of doing it.

对于正确"方式,请参阅 numpy.ndarray.sort

For the "correct" way see the order keyword argument of numpy.ndarray.sort

但是,您需要将数组视为具有字段的数组(结构化数组).

However, you'll need to view your array as an array with fields (a structured array).

如果您最初没有使用字段定义数组,那么正确"的方法会非常难看...

The "correct" way is quite ugly if you didn't initially define your array with fields...

举个简单的例子,对它进行排序并返回一个副本:

As a quick example, to sort it and return a copy:

In [1]: import numpy as np

In [2]: a = np.array([[1,2,3],[4,5,6],[0,0,1]])

In [3]: np.sort(a.view('i8,i8,i8'), order=['f1'], axis=0).view(np.int)
Out[3]: 
array([[0, 0, 1],
       [1, 2, 3],
       [4, 5, 6]])

就地排序:

In [6]: a.view('i8,i8,i8').sort(order=['f1'], axis=0) #<-- returns None

In [7]: a
Out[7]: 
array([[0, 0, 1],
       [1, 2, 3],
       [4, 5, 6]])

@Steve's 确实是最优雅的方式,据我所知......

@Steve's really is the most elegant way to do it, as far as I know...

此方法的唯一优点是order"参数是用于对搜索进行排序的字段列表.例如,您可以通过提供 order=['f1','f2','f0'] 按第二列、第三列和第一列排序.

The only advantage to this method is that the "order" argument is a list of the fields to order the search by. For example, you can sort by the second column, then the third column, then the first column by supplying order=['f1','f2','f0'].

这篇关于按列对 NumPy 中的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆