How to use Pandas to take multi year average in Python

时间:2015-07-28 22:52:05

标签: python numpy pandas time-series

I have a large data set with data from multiple locations (given in lat/long) over 80 years. I am trying to calculate a 10 year average for both column a and b from each site for the entire span of the time frame. Below is a sample of of the data table.

     Lat       Long Year Month Day      a      b
46.90625 -115.46875 1950    01  01 0.0000 1.1335
46.90625 -115.46875 1950    01  02 0.0000 1.1276 
46.90625 -115.46875 1950    01  03 0.0000 1.1213

Here is a sample of what I have tried but keep getting lost on.

fname = output1
df = pandas.read_table(output1)  
lat_long_group = df.groupby(['Lat','Long','Year']).agg(['mean','count'])
monthly_average = lat_long_group.aggregate({'a':numpy.mean,
                                            'b': numpy.mean})

1 个答案:

答案 0 :(得分:4)

首先,根据Pandas时间戳创建一个列:

df = df.dropna()
df['date'] = df.apply(lambda x: pd.Timestamp('{year}-{month}-{day}'
                                .format(year=int(x.Year), 
                                        month=int(x.Month), 
                                        day=int(x.Day))), 
                      axis=1)

接下来,根据Lat和Long的元组对设置您的位置。

df['Location'] = zip(df.Lat, df.Long)

现在,删除冗余数据。

df.drop(['Year', 'Month', 'Day', 'Lat', 'Long'], axis=1, inplace=True)

我们现在可以按日期和地点来调整数据。您的新DataFrame现在已在日期编制索引:

df2 = df.pivot(index='date', columns='Location')

交换新列的级别(以便位置位于值的顶部)。

df2.columns = df2.columns.swaplevel('Location', None)

最后,使用resample获取十年期间数据的平均值:

>>> df2.resample('10A', how='mean')  # 'A'=Annual, '10A'=TenYears
Location    (46.90625, -115.46875)          
                                 a         b
date                                        
1950-12-31                       0  1.127484
1960-12-31                       0  1.127467
1970-12-31                       0  1.127467
1980-12-31                       0  1.127467
1990-12-31                       0  1.127467
2000-12-31                       0  1.127467
2010-12-31                       0  1.127467
2020-12-31                       0  1.127467
2030-12-31                       0  1.127467
2040-12-31                       0  1.127452

我使用了30k行的相同数据(当然除了日期),但你可以看到这个过程是如何工作的。

请注意,数据会被分解为十年块,因此您的数据可能在两端都有存根(例如,如果您的数据始于1947年,则第一期仅为3 - 4年。