【问题标题】:Create climatology from pandas dataframe (append the mean by day-of-year)从 pandas 数据框创建气候学(按年添加平均值)
【发布时间】:2023-04-07 08:08:01
【问题描述】:
import pandas as pd
import pdb, random

dates = pd.date_range('1950-01-01', '1953-12-31', freq='D')
data  = [int(1000*random.random()) for i in xrange(len(dates))]
cum_data = pd.Series(data, index=dates)

cum_data.head()
    1950-01-01    310
    1950-01-02    477
    1950-01-03    401
    1950-01-04    896
    1950-01-05     65
...
    1951-01-01    320
...
    1952-01-01    330
...
    1953-01-01    340

# Compute climatology
cum_data.groupby([cum_data.index.month, cum_data.index.day]).mean()

我想计算此数据帧的气候学,即找到对应于 1 月 1 日(1950 年至 1953 年)的所有值的平均值,然后将平均值附加到 1954 年 1 月 1 日期间的数据帧到 1960 年 12 月 31 日。我该怎么做?

预期输出应该是 1950 年到 1953 年的原始数据集。1954 年 1 月 1 日应该是 1950 年、1951 年、1952 年、1953 年 1 月 1 日的平均值。在这种情况下:

    1954-01-01    325
...
    1955-01-01    325
...
...
    1960-01-01    325

所以, 1954 年 1 月 1 日等于 1955 年 1 月 1 日 ... 1960 年 1 月 1 日。其他所有日子也是如此。

【问题讨论】:

  • 你的预期输出是什么?
  • 这只是按一年中的一天计算平均值。这是基本的聚合。有大量现有的重复帖子。
  • 感谢 smci,我正在计算一年中的平均值,问题是如何将其附加到现有数据框中以获取新的一组年份(1954 年到 1960 年)
  • 我明白了,您想计算 1950-3 年的一年中的一个单一平均值,然后在 1954 年和 1955 年的每一年中将该平均值广播到该年的那一天。 .. 1960
  • @user308827 你找到相同问题的解决方案了吗?

标签: python pandas aggregate


【解决方案1】:

您可以在一年内使用resample 函数AS

In [8]: cum_data.resample('AS', how='mean')
Out[8]:
1950-01-01    502.169863
1951-01-01    503.698630
1952-01-01    503.185792
1953-01-01    504.961644
Freq: AS-JAN, dtype: float64

将此结果存储到tmp

In [9]: tmp = cum_data.resample('AS', how='mean')

将索引更改为所需的时间范围

In [10]: tmp.index = (pd.date_range('1954-01-01', '1957-01-01', freq='AS'))

In [11]: tmp
Out[11]:
1954-01-01    502.169863
1955-01-01    503.698630
1956-01-01    503.185792
1957-01-01    504.961644
Freq: AS-JAN, dtype: float64

也填写每日日期。

In [12]: tmp = tmp.reindex(pd.date_range('1954-01-01', '1957-12-31', freq='D')).ffill()

In [13]: tmp.head()
Out[13]:
1954-01-01    502.169863
1954-01-02    502.169863
1954-01-03    502.169863
1954-01-04    502.169863
1954-01-05    502.169863
Freq: D, dtype: float64

然后,追加到cum_data

In [14]: cum_data.append(tmp)
Out[14]:
1950-01-01    430
1950-01-02    125
1950-01-03    371
1950-01-04    906
1950-01-05    504
...
1957-12-28    504.961644
1957-12-29    504.961644
1957-12-30    504.961644
1957-12-31    504.961644
Length: 2922

【讨论】:

  • 谢谢,不过我想将其附加到原始数据帧中,并将时间段从 1954 年更新到 1960 年
  • 另外,我希望它可以在一年中的所有日子里工作,而不是一月
  • 感谢@John,这几乎是完美的。我遇到的问题是将数据一直延伸到 1960 年,您的解决方案可以做到吗?
  • 将第 12 行替换为 tmp = tmp.reindex(pd.date_range('1954-01-01', '1960-12-31', freq='D')).ffill()
  • 是的,您将如何填写年份平均值的每日值?
猜你喜欢
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2019-02-16
  • 2020-04-09
  • 2018-11-16
相关资源
最近更新 更多