我有以下部分輸入文件(擁有超過500行):如何獲得平均爲特定列表元素
L1, a, b, 10, 20, pass,
L1, c, d, 11, 21, pass,
L1, e, f, 12, 22, pass,
L1, a, b, 13, 23, pass,
L1, e, f, 14, 34, pass,
我想獲得的平均重複的,也就是輸出如下:
(其中爲L1,A,b,11.5 =(10 + 13)/ 2,21.5 =(20 + 23)/ 2)
L1, a, b, 11.5, 21.5
L1, c, d, 11, 21
L1, e, f, 13, 28
我當前初學者Python代碼是如下 - 仍在努力調整它更好
import csv
from collections import defaultdict
import numpy as np
dd = defaultdict(list)
with open("mean.csv") as input_file:
for row in csv.reader(input_file):
dd[tuple(row[:3])].append(float(row[3]))
dd[tuple(row[:3])].append(float(row[4]))
for k, v, m in dd.iteritems():
if len(v) > 1:
print (' '.join(k), np.mean(v), np.mean(m))
我得到的錯誤是:
Traceback (most recent call last):
File "average.py", line 11, in <module>
for k, v, m in dd.iteritems():
ValueError: need more than 2 values to unpack
你想使用代碼片段mtrw張貼到我的答案 - 並保持'爲k,v in ...'因爲它... – 2012-07-25 16:00:47