You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中不改变原行序对多维字符串数组按指定列降序排序

问题

现有NumPy多维数组如下:

import numpy as np
x = np.array([['PP Mango', 0.25, 0.75, 'PP'],
       ['PP Nectarine', 0.25, 0.75, 'PP'],
       ['Lemon', 0.25, 0.75, 'Loose'],
       ['PP Peach', 0.25, 0.75, 'PP'],
       ['Orange Navel', 0.25, 0.75, 'Loose'],
       ['PP Cherries', 0.25, 0.75, 'PP']], dtype=object)

需求:按第4列(x[:,3],值仅为'PP'或'Loose')降序排序,且不改变同组内原行的顺序。

尝试代码:

x[x[:,3].argsort()][::-1]  # 该代码会打乱同组内的原始行顺序,不符合要求

预期输出:

x = np.array([['PP Mango', 0.25, 0.75, 'PP'],
       ['PP Nectarine', 0.25, 0.75, 'PP'],
       ['PP Peach', 0.25, 0.75, 'PP'],
       ['PP Cherries', 0.25, 0.75, 'PP'],
       ['Lemon', 0.25, 0.75, 'Loose'],
       ['Orange Navel', 0.25, 0.75, 'Loose']], dtype=object)
解决方案

原因分析

你之前用的argsort()默认采用快速排序,属于不稳定排序——相同键值的元素会被重新打乱顺序。要实现需求,必须用稳定排序或者直接分组拼接。


方法1:稳定排序实现

利用numpy.argsort的kind='mergesort'参数启用稳定排序,配合自定义排序键实现降序:

import numpy as np

# 将'PP'映射为1,'Loose'映射为0,方便排序
sort_key = np.where(x[:,3] == 'PP', 1, 0)
# 用归并排序(稳定排序)得到升序索引,反转后即为降序且保留原顺序的索引
sorted_indices = sort_key.argsort(kind='mergesort')[::-1]
result = x[sorted_indices]

方法2:分组拼接(更直观)

直接提取原数组中'PP'组和'Loose'组的行,按要求顺序拼接,完全保留原组内顺序:

pp_rows = x[x[:,3] == 'PP']
loose_rows = x[x[:,3] == 'Loose']
result = np.vstack([pp_rows, loose_rows])

这种方法适合仅两类分组的场景,逻辑简单直接,不会有排序导致的顺序打乱问题。

内容的提问来源于stack exchange,提问作者user12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:25:20