[英]How to manipulate data in a text file
我正在尝试制作一个程序,该程序需要一个大的整数数据文件,并以另一种格式创建一个新的csv,其中它需要30行的x,y,z
,并将它们合并为一行。
大型数据集的格式为( timestamp, x,y,z
)
例如:
0.000, 5, 6, 8,
1.000, -6, 7, 9,
2.000, -15, 25, 23,
要么:
timestamp, x1, y1, z1
timestamp, x2, y2, z2
timestamp, x3, y3, z3
新的数据集将如下所示:
delta timestamp, x1, y1, z1, x2, y2, z2, x3, y3, z3....x30, y30, z30,
delta timestamp, x31, y31, z31, x32, y32, z32, x33,... x60, y60, z60,
等等。(每行包含30 x,y,z
)
我想到了可能每30行添加一个\\ n,然后用逗号替换每行。 而且我下面的代码不起作用。 它只是在新数据看起来像这样的地方加了一个逗号:
timestamp, x1, y1, z1,, timestamp, x2, y2, z2,, timestamp...
你们有什么主意吗?
list = []
import csv
i=0
results = []
with open('bikefall.csv', newline='') as inputfile:
for row in csv.reader(inputfile):
i+=1
if i%30==0:
results.append(row)
results.append('\n')
else:
results.append(row)
print("\n".join([item.replace('\n', ',') for item in
open('bikefall.csv').read().split('\n\n')]))
我不知道您如何计算增量,所以我只放了一个占位符函数。
关于你的代码,你可以使用改进一点点enumerate
,所以你不必更新i
手动。
您还可以使用切片符号在csv文件中获取每行的前4个项目。
import csv
def calculate_delta(timestamps):
pass
output = ""
with open('bikefall.csv', "r") as inputfile:
timestamps = []
results = []
for i, row in enumerate(csv.reader(inputfile)):
timestamp, x, y, z = row[:4]
timestamps.append(timestamp)
results.extend((x, y, z))
if len(timestamps) == 30:
delta = calculate_delta(timestamps)
str_timestamps = ", ".join(results)
output += "{}, {}\n".format(delta, str_timestamps)
timestamps = []
results = []
print(output)
这段代码有一个错误,当CSV中只有29行时会发生什么?
这29行将被忽略,因此您仍然需要检查当前行是否为csv文件中的最后一行,并进行相应处理。
一种方法是一次读取30
块的CSV文件。 然后合并这些行。 我假设delta
是通过从每个块的最后一个时间戳减去第一个时间戳来计算的(另一种可能是每个块的开始之间存在差异,所以第一个为0?):
from itertools import zip_longest
import csv
f_input = open('bikefall.csv', newline='')
f_output = open('output.csv', 'w', newline='')
with f_input, f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
for rows in zip_longest(*[iter(csv_input)] * 30, fillvalue=None):
rows = [[float(row[0])] + row[1:] for row in rows if row]
delta = rows[-1][0] - rows[0][0]
combined = [delta]
for row in rows:
combined.extend([row[1], row[2], row[3]])
csv_output.writerow(combined)
分组基于Python文档中的itertools grouper grouper()
配方。
这是zip
的完美工作。 这是一个解决方案,比以前的答案多了pythonic:
with open('bikefall.csv') as inputfile:
# version using csv reader
matrix = [[line[0],','.join(line[1:])] for line in csv.reader(inputfile)]
# version using standard text file reader
#matrix = [line.strip().split(',', maxsplit=1) for line in inputfile]
stamps, coords = zip(*matrix) # split matrix into stamps and coords
for n in range(0, len(stamps), 30):
print(','.join((stamps[n],) + coords[n:n+30]))
注意:由于采用了切片符号,因此可以自动管理可能少于30个项目的最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.