Gabriel Butoeru Gabriel Butoeru - 2 months ago 20
Python Question

Sort csv columns?

I have a CSV file that looks like:

Timestamp;A;O;P;M;
22:05;5;7;2;1
22:10;2;3,4;7
22:15;7;4;3;2


With a python script I would like to order the header (except the timestamp. it has to be the first column). What I mean is:

Timestamp;A;M;O;P;
22:05;5;1;7;2
22:10;2;7;3;4
22:15;7;2;4;3


How can I do it? I don't have any code because I can't figure out how to do it.

Answer

You can do it with NumPy!

import numpy as np

a = np.loadtxt('a.txt', dtype=str, delimiter=';')
s = a[0].argsort() # produces the indexes which would sort the header
s = np.append(0, s[s!=0]) # put 0 at the front again, that's Timestamp
final = a[:,s]
np.savetxt('final.txt', final, fmt='%s', delimiter=';')