我的数组如下所示:

x = 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)
   

我正在try 对这个多维数组进行排序.第4个元素x[:,3],它是降序为103的字符串(始终为‘PP’或‘Loose’).

Tried code:

x[x[:,3].argsort()][::-1]       #but this shuffles the original array row order within 4th element which should not happen

Expected Output:

x = 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)

推荐答案

使用列表排序时,只需要一个排序关键字来比较第四个元素是否"松散".

Pythonsort的 solidity 保证了它不会在不需要的情况下移动元素.

lst = [['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']]

lst = sorted(lst,key=lambda x:x[3]=='Loose')
print(lst)

打印:

[['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']]

这是一个非麻木的解决方案,但它是有效的.然后转换回NumPy数组:array(lst)

Python-3.x相关问答推荐

在numpy. linalg的qr之后使用scipy. integrate中的solve_ivp时出现了一个奇怪的错误

如何通过Pandas为不同的列集垂直设置列数据?

将两列的乘积连续添加到一列的累积和中

Pandas教程:如何更新行内数值的位置

如何对具有多个列值的 pandas 数据框进行数据透视/数据透视表

如何使用 django rest 框架在 self forienkey 中删除多达 n 种类型的数据?

正则表达式来识别用 Python 写成单词的数字?

spaCy 中的匹配模式返回空结果

从日志(log)文件中查找延迟最低的用户

Python:获取未绑定的类方法

Pythonic,自定义警告

为什么Pandas会在 NaN 上合并?

判断对 python 3 支持的要求

Jupyter Notebook - 在函数内绘图 - 未绘制图形

Python的max函数有多高效

try 在 Windows 10 高 DPI 显示器上解决模糊的 tkinter 文本 + zoom ,但担心我的方法不是 Pythonic 或不安全

在python中打印下标

如何正确创建自定义文本编解码器?

TypeError:只有整数标量数组可以转换为标量索引

如何创建一个永远在其上运行滚动协程的事件循环?