I've a data.csv file which looks as follows.
-1.95e+01 -2.30e-01 -2.56e-01 4.44e+01
-1.95e+01 -2.30e-01 -7.68e-01 4.48e+01
-2.00e+01 -2.30e-01 -2.56e-01 3.41e+01
-2.00e+01 -2.30e-01 -7.69e-01 3.46e+01
-2.10e+01 -9.92e+00 1.00e+01 9.66e+01
-2.10e+01 -9.92e+00 2.30e+00 4.29e+01I'd like to have a result.csv file such that if the value in the first column is the same, grab all the data in the first four columns (there are 4 columns) and save it in result.csv file. Then the next equal values and save it in the next four columns. For example my result.csv should look like
-1.95e+01 -2.30e-01 -2.56e-01 4.44e+01 -2.00e+01 -2.30e-01 -2.56e01 3.41e+01 -2.10e+01 -9.92e+00 1.00e+01 9.66e+01
-1.95e+01 -2.30e-01 -7.68e-01 4.48e+01 -2.00e+01 -2.30e-01 -7.69e-01 3.46e+01 -2.10e+01 -9.92e+00 2.30e+00 4.29e+01My very basic attempt is as follows:
with open('data.csv', 'r') as f: csv_reader = csv.reader(f, delimiter='\t') for col in csv_reader: i = 0 if col[0] == "Next value of the same column": 'don't know how to fix #Grab all the values which have same value in the first column else: #Grab next values which have same value in the first column i += 1 3 1 Answer
import csv
with open('data.csv', 'r') as _: input = csv.reader(_, delimiter='\t') output = [[]] previous_col0 = None line_n = 0 for cols in input: if cols[0] == previous_col0: line_n += 1 else: previous_col0 = cols[0] line_n = 0 if len(output) <= line_n: output += [[]] output[line_n] += cols