作者:手机用户2502939003 | 来源:互联网 | 2023-07-16 17:09
我有一个看起来像这样的CSV文件:
row1
1
3
5
8
我需要从一行到它的跟随者行获得不同之处:
row1
1 1-1 = 0
3 3-1 = 2
5 5-3 = 2
8 8-5 = 3
然后得到结果(0,2,3)
的平均值。不是寻找一个直接的答案,而是一个起点
这里是一种方法:
with open("test.csv") as f:
lines = f.readlines()
# the first row is always 0
result = [0,] + [ int(lines[x]) - int(lines[x-1]) for x in range(1,len(lines))]
#print the array of differences
print(result)
#print the average
print(sum(result)/len(result))
,
如果只想作为起点:
with open("yourfile.csv","r") as f:
lines = f.readlines()
for index,line in enumerate(lines[1:]):
number = int(line)
if index == 0:
# magic for the first row
else:
# magic for a normal row
您必须处理不同的第一行,因为您不能回头,因为它是第一行。
编辑:解决方案
with open("input.csv","r") as f:
lines = f.readlines()
output = [0]
header = lines[0]
data = [int(number) for number in lines[1:]]
for index,number in enumerate(data[1:],1):
output.append(number-data[index-1])
print(output)
print("Average: {}".format(sum(output)/len(output)))
输出:
[0,2,3]
Average: 1.75