Skip to main content
 首页 » 编程设计

python之NumPy 的 python : Sorting columns of an array in alphabetical order

2025年02月15日13soundcode

我目前正在使用 Python 3 和 Numpy。我有一个使用 numpy.genfromtxt("textfile.txt", names=True) 创建的结构化数组,我想按字母顺序对列进行排序。

  • 第一行包含列的名称。

  • 其他列包含每个实例的伴随值。

我只想将列的顺序切换为列名的字母顺序。 例如,现在列的顺序是 'year'、'population'、'area' 我希望它变成 '面积','人口','年份'。 在此先感谢您的帮助!

请您参考如下方法:

对于下面的numpy数组,答案是:

import numpy as np 
 
 
x = np.array([(2015, 34, 12, 13), (2016, 41, 6, 7), (2016, 17, 5, 2), 
       (2013, 21, 8, 19), (2013, 1, 81, 9)],  
      dtype=[('year', '<i8'), ('tigers', '<i8'), ('monkeys', '<i8'), ('cows', '<i8')]) 
 
x[numpy.sort(x.dtype.names)] 
 
# Output: 
array([(13, 12, 34, 2015), (7, 6, 41, 2016), (2, 5, 17, 2016), 
       (19, 8, 21, 2013), (9, 81, 1, 2013)],  
      dtype=[('cows', '<i8'), ('monkeys', '<i8'), ('tigers', '<i8'), ('year', '<i8')])