Reputation: 131
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.
Upvotes: 0
Views: 1241
Reputation: 1139
Hi this post might help you. Check this link. sort csv by column
https://stackoverflow.com/questions/2100353/sort-csv-by-column
Upvotes: 0
Reputation: 249642
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=';')
Upvotes: 2
Reputation: 174748
You mean something like this?
import csv
with open('old.csv', 'r') as i, open('new.csv', 'w') as o:
reader = csv.reader(i, delimiter=';')
writer = csv.writer(o, delimiter=';')
for row in reader:
writer.writerow([row[0], row[1], row[4], row[2], row[3]])
Upvotes: 1