我有一个data.csv
如下所示的文件。
-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+01
我希望有一个result.csv
文件,如果第一列中的值相同,则抓取前四列(共有 4 列)中的所有数据并将其保存在result.csv
文件中。然后抓取下一个相等的值并将其保存在接下来的四列中。例如,我的result.csv
应该是这样的
-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+01
我最基本的尝试如下:
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
答案1
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