關於如何按給定列對整個數組/重新排列進行排序,我有一個相當簡單的問題。例如,假設數組:按列排序python數組/重新排列
import numpy as np
data = np.array([[5,2], [4,1], [3,6]])
我想第一列對數據進行排序,返回:
array([[3,6], [4,1], [5,2]])
關於如何按給定列對整個數組/重新排列進行排序,我有一個相當簡單的問題。例如,假設數組:按列排序python數組/重新排列
import numpy as np
data = np.array([[5,2], [4,1], [3,6]])
我想第一列對數據進行排序,返回:
array([[3,6], [4,1], [5,2]])
使用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]])
您正在尋找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]]
排序在第二列中使用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]]
>>>
這是有點棘手:
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
我在這裏找到這個配方: