3

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!

7
  • Look into numpy.argsort. Commented Nov 28, 2016 at 14:04
  • Thanks for helping out! I haven't managed to use argsort to order alphabetically. Do I need to tune a parameter? Commented Nov 28, 2016 at 14:13
  • 1
    Abdou, I think you misunderstood the question. He does not want to sort the records in the array, he wants to reorder the columns. Commented Nov 28, 2016 at 14:14
  • @V.K. I just realized. Select the arrays by name and stack or concatenate them together in the order you want. Commented Nov 28, 2016 at 14:27
  • @Frederiquevdb, can you please provide a toy dataset to work with? Commented Nov 28, 2016 at 15:06

1 Answer 1

2

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')])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.