排序numpy混合类型矩阵

2024-06-16 10:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对每列包含相同类型但每列可能有不同类型的(更广泛的)矩阵进行排序。执行此排序时,应使一行中的所有列保持在一起,但行顺序遵循已定义列的值

[ 
[1, 0, 0.25,'ind1', 'pop2', 0.56],
[2, 0, 0.35,'ind2', 'pop2', 0.58],
[1, 0, 0.23,'ind1', 'pop1', 0.66],
...
]

这里我执行一个按列2排序的算法(浮点列)

^{pr2}$

如果列包含字符类型,它会改变吗? 谢谢你的帮助和建议,但我还是查了lexsort,sort,argsort…但可能是用错了方法。 编辑:我不知道为什么,但是如果我的矩阵定义为numpy.matrix公司(),argsort()方法添加一个维度(因此是三维结果),如果使用数字阵列(). 如果它能帮助更多的读者。在


Tags: 方法算法类型定义排序顺序矩阵字符
1条回答
网友
1楼 · 发布于 2024-06-16 10:37:03

如果数据类型具有命名字段,则可以使用numpy.排序,并在“order”参数中指定要排序的字段名:

import numpy 

fieldTypes = ['i4', 'i4', 'f8', 'S4', 'S4', 'f8'] # data types of each field
fieldNames = ['a', 'b', 'c', 'd', 'e', 'f'] # names of the fields, feel free to give more descriptive names

myType = numpy.dtype(zip(fieldNames, fieldTypes)) # Create a numpy data type based on the types and fields

a = numpy.array([(1, 0, 0.25,'ind1', 'pop2', 0.56),
(2, 0, 0.35,'ind2', 'pop2', 0.58),
(1, 0, 0.23,'ind1', 'pop1', 0.66)], dtype=myType) # Create the array with the right dtype

print numpy.sort(a, order=['c']) # sort based on column 'c'

请注意,如果要创建空缓冲区或从现有文件/缓冲区加载numpy数据,您仍然可以将其转换为具有命名字段的dtype。在

如果您没有命名字段,this答案可以帮助您,我推荐@Steve Tjoa建议的方法:

^{pr2}$

相关问题 更多 >