我是Python新手,有一组值,如下所示:
(3, '655')
(3, '645')
(3, '641')
(4, '602')
(4, '674')
(4, '620')
使用以下CSV文件生成的python.6:
import csv
import time
with open('file.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
date = time.strptime(row[3], "%a %b %d %H:%M:%S %Z %Y")
data = date, row[5]
month = data[0][1]
avg = data[1]
monthAvg = month, avg
print monthAvg
我想做的是得到基于键的值的平均值:
(3, 647)
(4, 632)
我最初的想法是编一本新词典。你知道吗
loop through the original dictionary
if the key does not exist
add the key and value to the new dictionary
else
sum the value to the existing value in the new dictionary
我还得记下钥匙的数目,这样我才能得出平均数。似乎有很多工作-我不确定是否有一个更优雅的方式来完成这一点。你知道吗
谢谢你。你知道吗
使用字典理解,其中
items
在元组对列表中:使用
pandas
,它是专门为做这类事情而设计的,这意味着您可以用少量代码来表达它们(您要做的是一行代码)。此外,当给定大量值时,它将比任何其他方法都快得多。你知道吗提供:
下面是一个多行版本,显示发生了什么:
此外,如果您想使用
csv
文件,就更容易了,因为您不需要自己解析csv
文件(我对不知道的列使用虚构的名称):可以使用^{} 创建具有唯一键和值列表的字典:
然后使用列表来创建预期的对:
在代码中,您可以执行以下操作:
相关问题 更多 >
编程相关推荐