如何使用 Pandas 在 Python 中获取多年平均值

How to use Pandas to take multi year average in Python

我有一个大型数据集,其中包含来自多个位置(在 lat/long 中给出)超过 80 年的数据。我正在尝试计算整个时间范围内每个站点的 a 列和 b 列的 10 年平均值。以下是数据示例 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

这是我尝试过但一直迷路的示例。

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})

首先,根据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)

接下来,根据纬度和经度的元组对设置您的位置。

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 年。