Reputation: 69
I'm currently working with Python 3 and Numpy. I have a structured array created by using numpy.genfromtxt("textfile.txt", names=True)
and I want to sort the columns in alphabetical order.
The first row contains the names of the columns.
The other columns contain the accompanying values per instance.
I simply want to switch the order of the columns to the alphabetical order of the column names.
For instance, now the order of the columns is 'year'
, 'population'
, 'area'
and I want it to become 'area', 'population', 'year'
.
Thanks in advance for helping out!
Upvotes: 3
Views: 6236
Reputation: 69
For the following numpy array, the answer is:
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')])
Upvotes: 2