Numpy 数组复合排序——mX4列,根据多列组合排序
一、 Numpy 仅根据某列对 array(mX4)整体排序用argsort
import numpy as np
data = np.array([[1, 5, 2, 4, 10], [9, 6, 8, 4, 5], [2, 3, 4, 6, 3], [7, 6, 8, 4, 6]])
print(' before---- ')
print(data)
data = data[data[:, 0].argsort()]
print('根据第1列排序 after: ')
print(data)
运行结果:
二、mX4根据多列组合排序(先根据x排序,x相同根据y排序,y相同根据z排序)
分以下三步进行,源代码见底部:
- np array(array) 转array(tuple) [(1,2,3,4),(5,6,7,8),…] ----> [(1,2,3,4),(5,6,7,8),…]
m2A = []
for i in range(0, len(inFile)):
m2A.append((inFile[i][0], inFile[i][1], inFile[i][2], inFile[i][3]))
- np 对array(tuple) 进行 多列组合排序(先根据x排序,再根据y排序,再根据z排序) m2A: [(1,2,3,4),(5,6,7,8),…]
dtype = [('x', float), ('y', float), ('z', float), ('i', int)]
tuple1 = np.array(m2A, dtype)
tuple1 = np.sort(tuple1, order=['x', 'y', 'z'])
-
np array(tuple) 转 array(array)
该过程包括俩步:
(1) np array 递归转为 tuple [(1,2,3,4),(5,6,7,8),…] ----> ((1,2,3,4),(5,6,7,8),…)
(2) np tuple 转 array [(1,2,3,4),(5,6,7,8),…] —> [[1,2,3,4],[5,6,7,8],…]
inFile = np.array(totuple(tuple1)) # 先整体转为元组,再转多维数组
import numpy as np
np.set_printoptions(suppress=True)
def totuple(a):
try:
return tuple(totuple(i) for i in a)
except TypeError:
return a
data = np.array([[423999.72382051, 4421127.27096031, 83.313, 7.],
[423993.12782051, 4421123.49396031, 83.276, 23.],
[423993.05882051, 4421122.56596031, 84.28, 82.],
[423992.95382051, 4421123.20896031, 83.293, 15.],
[423993.08082051, 4421122.47896031, 84.429, 100.]])
print('排序前: ',data.shape,data)
m2A = []
for i in range(0, len(data)):
m2A.append((data[i][0], data[i][1], data[i][2], data[i][3]))
dtype = [('x', float), ('y', float), ('z', float), ('i', int)]
tuple1 = np.array(m2A, dtype)
tuple1 = np.sort(tuple1, order=['x', 'y', 'z'])
print(tuple1.shape)
inFile = np.array(totuple(tuple1)) # 转为元组,转array
print('排序后:', data)