gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:51 24 4
gpt4 key购买 nike

我有一个大型数据集,其中包含来自多个位置(以纬度/经度给出)超过 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)

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

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 行使用了相同的数据(当然,日期除外),但您可以看到该过程是如何工作的。

请注意,数据甚至被分成十年的 block ,因此您的数据两端可能都有 stub (例如,如果您的数据始于 1947 年,那么第一个周期将只有 3-4 年。

关于python - 如何使用 Pandas 在 Python 中获取多年平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com