编辑:关于工作代码,请参阅我文章的末尾,从zeekayhere获得。
我有一个CSV文件,有两列(电压和电流)。因为电压被记录到许多有效数字,而电流只有2,所以随着电压值的变化有许多相同的电流值。这对编程并不重要,但我只是解释数据是如何物理获得的。我要执行以下操作:
只要第二列(电流)的值不变,就将第一列(电压)的值收集到一个列表中,并对其进行平均。然后将一行写入一个新的CSV文件,该文件是第一列中电压的平均值和第二列中不变的恒流值。换言之,如果有20行的电流没有变化(比如说它是6 uA),则对20个相应的电压值进行平均(比如这个平均值是600 mV),并在一个新的csv文件中生成一行,该文件读取('0.6','0.000006')。然后我想继续遍历正在读取的csv,对每组固定电流重复上述过程。
到目前为止,我已经得到了以下代码,但我不确定我是否在正确的轨道上:
import sys, csv
with open('filetowriteto.csv','w') as avg:
loadeddata = open('filetoreadfrom.csv','r')
writer=csv.writer(avg)
readloaded=csv.reader(loadeddata)
listloaded=list(readloaded)
oldcurrent=listloaded[0][1]
for row in readloaded:
newcurrent = row[1]
biaslist = []
if newcurrent == oldcurrent:
biaslist.append(row[0])
else :
biasavg = float(sum(biaslist))/len(biaslist)
writer.writerow([biasavg,newcurrent])
newcurrent = row[1]
然后我不知道该去哪里。
编辑:看来泽凯正朝着我想做的方向前进。我正在尝试实现他的itertools.groupby()方法,但目前正在生成一个空白文件。这是我到目前为止的新代码:
import sys, csv, itertools
with open('VI_avg(12).csv','w') as avg: # this is the file which gets written
loadeddata = open('VI(12).csv','r') # this is the file which is read
writer=csv.writer(avg)
readloaded=csv.reader(loadeddata)
listloaded=list(readloaded)
oldcurrent=listloaded[0][1] # looks like this is no longer required
for current, row in itertools.groupby(readloaded, lambda x: x[1]):
biaslist = [float(x[0]) for x in row]
biasavg = float(sum(biaslist))/len(biaslist)
# write it out
writer.writerow(biasavg, current)
假设正在打开的CSV文件类似于以下内容(简称示例):
0.595417,0.000065
0.595177,0.000065
0.594937,0.000065
0.594697,0.000065
0.594457,0.000065
0.594217,0.000065
0.593977,0.000065
0.593737,0.000065
0.593497,0.000064
0.593017,0.000064
0.592777,0.000064
0.592537,0.000064
0.592297,0.000064
0.587018,0.000064
0.586778,0.000064
0.586538,0.000063
0.586299,0.000063
0.586059,0.000063
0.585579,0.000063
0.585339,0.000063
0.585099,0.000063
0.584859,0.000063
0.584619,0.000063
0.584379,0.000063
0.584139,0.000063
0.583899,0.000063
0.583659,0.000063
最终更新:这是工作版本,从zeekay获得:
import csv
import itertools
with open('VI(12).csv') as input, open('VI_avg(12).csv','w') as output:
reader = csv.reader(input)
writer = csv.writer(output)
for current, row in itertools.groupby(reader, lambda x: x[1]):
biaslist = [float(x[0]) for x in row]
biasavg = float(sum(biaslist))/len(biaslist)
writer.writerow([biasavg, current])
最佳答案
当您阅读csv时,可以使用itertools.groupby
对结果进行分组,这样可以简化很多事情。根据您更新的示例:
import csv
import itertools
with open('VI(12).csv') as input, open('VI_avg(12).csv','w') as output:
reader = csv.reader(input)
writer = csv.writer(output)
for current, row in itertools.groupby(reader, lambda x: x[1]):
biaslist = [float(x[0]) for x in row]
biasavg = float(sum(biaslist))/len(biaslist)
writer.writerow([biasavg, current])
关于python - 如果另一列中的值未更改,如何在csv的一列中取平均值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9399050/