Numpy 数组复合排序——mX4列,根据多列组合排序
生活随笔
收集整理的這篇文章主要介紹了
Numpy 数组复合排序——mX4列,根据多列组合排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Numpy 數組復合排序——mX4列,根據多列組合排序
一、 Numpy 僅根據某列對 array(mX4)整體排序用argsort
import numpy as npdata = 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 npnp.set_printoptions(suppress=True)def totuple(a):try:return tuple(totuple(i) for i in a)except TypeError:return adata = 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)) # 轉為元組,轉arrayprint('排序后:', data)
運行結果如下:
總結
以上是生活随笔為你收集整理的Numpy 数组复合排序——mX4列,根据多列组合排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 并 查 集
- 下一篇: windows10+Python3.7安