我有一个关于如何按给定列对整个数组/重新排列进行排序的相当简单的问题。例如,给定数组:
import numpy as np
data = np.array([[5,2], [4,1], [3,6]])
我想按第一列排序数据:
array([[3,6], [4,1], [5,2]])
答案 0 :(得分:46)
使用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]])
答案 1 :(得分:11)
您正在寻找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]]
答案 2 :(得分:5)
这有点棘手:
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
我在这里找到了这个食谱:
答案 3 :(得分:4)
要对第二列进行排序,请使用itemgetter
>>> from operator import itemgetter
>>> data = [[5,2], [4,1], [3,6]]
>>> sorted(data)
[[3, 6], [4, 1], [5, 2]]
>>> sorted(data,key=itemgetter(1))
[[4, 1], [5, 2], [3, 6]]
>>>
答案 4 :(得分:1)
以下是适用于切片的扩展程序:
DECLARE @counter int = 1;
DECLARE @date date = '2020-04-29'
WHILE @counter <= 7
BEGIN
select datefromparts(year(@date), month(@date), @counter);
SET @counter = @counter + 1;
END
按行排序:
import numpy as np
x = np.array([[9, 1, 2],
[5, 3, 4],
[0, 5, 6]])
按列排序:
x[:, x[1,:].argsort()] # Sort by second row
array([[1, 2, 9]
[3, 4, 5]
[5, 6, 0]])