Python 使用时间信息计算元组值的年平均值

Python 使用时间信息计算元组值的年平均值,python,python-2.7,tuples,Python,Python 2.7,Tuples,我有以下形式的每日降水量值和时间信息: a = [(19500101,3.45),(19500102,1.2).......(19701231,1.4)] 我想用日期信息取它的年平均值。这可能是一个简单的解决方案。我试过如下。有什么建议吗 prcp=numpy.array(precipitation) time=numpy.array(time) yearly=numpy.zeros(prcp.shape) #-----------------Get annual means--------

我有以下形式的每日降水量值和时间信息:

a = [(19500101,3.45),(19500102,1.2).......(19701231,1.4)]
我想用日期信息取它的年平均值。这可能是一个简单的解决方案。我试过如下。有什么建议吗

prcp=numpy.array(precipitation)
time=numpy.array(time)
yearly=numpy.zeros(prcp.shape)

#-----------------Get annual means-----------------
for ii in xrange(len(time)):
    tt=time[ii]
    if ii==0:
        year_old=tt[0:4]
        index_start=ii
    else:
        #----------------new year----------------
        year=tt[0:4]
        if year != year_old:
            year_mean=numpy.mean(prcp[index_start:ii])
            yearly[index_start:ii]=year_mean
            year_old=month
            index_start=ii

    #----------------Get the last year----------------
    if ii==len(time)-1:
        year_mean=numpy.mean(prcp[index_start:])
        yearly[index_start:]=year_mean

您可以尝试
Pandas
进行聚合

import pandas as pd

a = [(19500101,3.45),(19500102,1.2), (19701231,1.4)]  
df = pd.DataFrame(a) # convert to dataframe                                
df[0] = pd.to_datetime(df[0], format='%Y%m%d') # create a datetime series    

df.groupby(df[0].map(lambda x: x.year)).mean() # groupby year and mean from g roups

          1
0
1950  2.325
1970  1.400

您可以使用以下代码段执行此操作:

首先,根据年份分离数据:

>>> list_of_data = [(19500101,3.45), (19500102,1.2), (19701231,1.4)]
>>> from collections import defaultdict
>>> data = defaultdict(list)
>>> for item in list_of_data:
...     data[str(item[0])[:4]].append(item[1])
现在,使用

>>> for key, value in data.iteritems():
...     print key, sum(value)/len(value)
... 
1950 2.325
1970 1.4

请注意,我在数据上运行了两次,@John对Pandas的回答可能会更快,如果您可以使用Pandas库。

我推荐
Pandas
,正如@John Galt建议的那样

如果您想要一个没有熊猫的python解决方案:

import numpy as np
a = [(19500101,3.45),(19500102,1.2).......(19701231,1.4)]
year=lambda x:int(x[0]/10**4)
years={year(x) for x in a}
annual_avg=dict()
for y in years:
   annual_avg[y]=reduce(np.mean,[x[1] for x in a if year(x)==y])

在我们找到你的请求背后的逻辑或者你所面临的问题之前,你能展示你迄今为止所做的努力吗?