Rearrange data in csv with Python -
i have .csv
file following format:
a b c d e f x1 x2 x3 x4 x5 x6 y1 y2 y3 y4 y5 y6 z1 z2 z3 z4 z5 z6
what want:
a x1 b x2 c x3 d x4 e x5 f x6 y1 b y2 c y3 d y4 e y5 f y6 z1 b z2 c z3 d z4 e z5 f z6
i unable wrap mind around built-in transpose functions in order achieve final result. appreciated.
you can melt dataframe using pandas:
import pandas pd df = pd.read_csv(csv_filename) >>> pd.melt(df) variable value 0 x1 1 y1 2 z1 3 b x2 4 b y2 5 b z2 6 c x3 7 c y3 8 c z3 9 d x4 10 d y4 11 d z4 12 e x5 13 e y5 14 e z5 15 f x6 16 f y6 17 f z6
a pure python solution follows:
file_out_delimiter = ',' # use '\t' tab delimited. open(filename, 'r') f, open(filename_out, 'w') f_out: headers = f.readline().split() row in f: pair in zip(headers, row.split()): f_out.write(file_out_delimiter.join(pair) + '\n')
resulting in following file contents:
a,x1 b,x2 c,x3 d,x4 e,x5 f,x6 a,y1 b,y2 c,y3 d,y4 e,y5 f,y6 a,z1 b,z2 c,z3 d,z4 e,z5 f,z6
Comments
Post a Comment