![](/img/trans.png)
[英]Python Pandas groupby or rolling multi year average summary statistics
[英]How to use Pandas to take multi year average in Python
80多年來,我有一個包含來自多個位置(以緯度/經度給出)的數據的大型數據集。 我試圖在整個時間范圍內計算每個站點的a和b列的10年平均值。 以下是數據表的示例。
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)
接下來,根據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年。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.