Numpy Python:按字母顺序对数组的列进行排序
Numpy Python: Sorting columns of an array in alphabetical order
我目前正在使用 Python 3 和 Numpy。我有一个使用 numpy.genfromtxt("textfile.txt", names=True)
创建的结构化数组,我想按字母顺序对列进行排序。
第一行包含列的名称。
其他列包含每个实例的伴随值。
我只想将列的顺序切换为列名的字母顺序。
例如,现在列的顺序是 'year'
、'population'
、'area'
,我希望它变成 'area', 'population', 'year'
。
在此先感谢您的帮助!
对于下面的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')])
我目前正在使用 Python 3 和 Numpy。我有一个使用 numpy.genfromtxt("textfile.txt", names=True)
创建的结构化数组,我想按字母顺序对列进行排序。
第一行包含列的名称。
其他列包含每个实例的伴随值。
我只想将列的顺序切换为列名的字母顺序。
例如,现在列的顺序是 'year'
、'population'
、'area'
,我希望它变成 'area', 'population', 'year'
。
在此先感谢您的帮助!
对于下面的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')])