按列排序Python数组/记录数组

36 投票
5 回答
54010 浏览
提问于 2025-04-16 22:18

我有一个比较简单的问题,想知道怎么根据某一列对整个数组或者记录数组进行排序。比如,给定这个数组:

import numpy as np
data = np.array([[5,2], [4,1], [3,6]])

我想根据第一列进行排序,返回的结果是:

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

5 个回答

6

这个有点棘手:

data[data[:,0].argsort()]

# data[:,n] -- get entire column of index n
# argsort() -- get the indices that would sort it
# data[data[:,n].argsort()] -- get data array sorted by n-th column

我在这里找到了这个方法:

链接

http://mathesaurus.sourceforge.net/matlab-numpy.html

14

你在寻找 operator.itemgetter 这个东西。

>>> from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

也就是说。

In [7]: a
Out[7]: [[5, 2], [4, 1], [3, 6]]

In [8]: sorted(a, key=operator.itemgetter(0))
Out[8]: [[3, 6], [4, 1], [5, 2]]
54

使用 data[np.argsort(data[:, 0])] 这个方法来排序,其中 0 是你想要排序的列的索引:

In [27]: import numpy as np

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

In [29]: col = 0

In [30]: data=data[np.argsort(data[:,col])]
Out[30]: 
array([[3, 6],
       [4, 1],
       [5, 2]])

撰写回答