根据键对字典中的值求平均值

2024-09-26 22:53:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

我还得记下钥匙的数目,这样我才能得出平均数。似乎有很多工作-我不确定是否有一个更优雅的方式来完成这一点。你知道吗

谢谢你。你知道吗


Tags: csvthecsvfileinimportdatadatedictionary
3条回答

使用字典理解,其中items在元组对列表中:

data = {i:[int(b) for a, b in items if a == i] for i in set(a for a, b in items)}
data = {a:int(float(sum(b))/float(len(b))) for a, b in data.items()} # averages

使用pandas,它是专门为做这类事情而设计的,这意味着您可以用少量代码来表达它们(您要做的是一行代码)。此外,当给定大量值时,它将比任何其他方法都快得多。你知道吗

import pandas as pd

a=[(3, '655'),
   (3, '645'),
   (3, '641'),
   (4, '602'),
   (4, '674'),
   (4, '620')]

res = pd.DataFrame(a).astype('float').groupby(0).mean()
print(res)

提供:

     1
0     
3  647
4  632

下面是一个多行版本,显示发生了什么:

df = pd.DataFrame(a)  # construct a structure containing data
df = df.astype('float')  # convert data to float values
grp = df.groupby(0)  # group the values by the value in the first column
df = grp.mean()  # take the mean of each group

此外,如果您想使用csv文件,就更容易了,因为您不需要自己解析csv文件(我对不知道的列使用虚构的名称):

import pandas as pd
df = pd.read_csv('file.csv', columns=['col0', 'col1', 'col2', 'date', 'col4', 'data'], index=False, header=None)
df['month'] = pd.DatetimeIndex(df['date']).month
df = df.loc[:,('month', 'data')].groupby('month').mean()

可以使用^{}创建具有唯一键和值列表的字典:

>>> l=[(3, '655'),(3, '645'),(3, '641'),(4, '602'),(4, '674'),(4, '620')]
>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> 
>>> for i,j in l:
...    d[i].append(int(j))
... 
>>> d
defaultdict(<type 'list'>, {3: [655, 645, 641], 4: [602, 674, 620]})

然后使用列表来创建预期的对:

>>> [(i,sum(j)/len(j)) for i,j in d.items()]
[(3, 647), (4, 632)]

在代码中,您可以执行以下操作:

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]
        d[month].append(int(avg))

     print [(i,sum(j)/len(j)) for i,j in d.items()]

相关问题 更多 >

    热门问题