Frederique
Frederique

Reputation: 69

Numpy Python: Sorting columns of an array in alphabetical order

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.

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

Answers (1)

Frederique
Frederique

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

Related Questions