Numpy 数组复合排序——mX4列,根据多列组合排序

50 篇文章 2 订阅
23 篇文章 0 订阅

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排序)

分以下三步进行,源代码见底部:

  1. 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]))
  1. 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'])
  1. 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)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛一枚~

您的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值