如何在Pandas中对各种快照进行降样,使之成为月度平均值?

问题描述 投票:1回答:1

我有一个数据框架,里面有不同时间段的累计总和,我想统一下采样到月平均数。有时,我有一个年度总结,我想将其下采样至 1/12季度数据下采样至 1/3,而月度数据根本不会被下采样。所以,如果我有下面的例子

1   2017-12-31  600
2   2018-12-31  1200
3   2109-03-31  330
4   2019-04-30  125
5   2019-05-31  126
6   2019-06-30  127
7   2019-09-30  360
8   2020-01-31  480

我想实现下采样数的和(期间值)的分割。

date    value
2017-12-31  600
2018-01-31  100
2018-02-28  100
2018-03-31  100
2018-04-30  100
2018-05-31  100
2018-06-30  100
2018-07-31  100
2018-08-31  100
2018-09-30  100
2018-10-31  100
2018-11-30  100
2018-12-31  100
2019-01-31  120
2019-02-28  110
2019-03-31  110
2019-04-30  125
2019-05-31  126
2019-06-30  127
2019-07-31  120
2019-08-31  120
2019-09-30  120
2019-10-31  120
2019-11-30  120
2019-12-31  120
2020-01-31  120

有没有一个内部的pandas函数或者同样简单的自定义函数可以实现这个功能?我可以想象,我将回填数值并除以重采样组的大小,但我还没有找到一个简单的方法来实现。

pandas time-series resampling downsampling
1个回答
1
投票

我已经设法解决了这个问题,虽然通过一个有点麻烦的方法。我还是希望有一个简单的方法。

  1. 输入df
[In] print(df):
[Out]: 
date    value
2017-12-31  600
2018-12-31  1200
2019-03-31  330
2019-04-30  125
2019-05-31  126
2019-06-30  127
2019-09-30  360
2020-01-31  480
  1. 重新取样和回填。
[In] res = df.set_index("date").resample("M").bfill()
[In] print(res)
[Out] 
date       value
2017-12-31 600
2018-01-31 1200
2018-02-28 1200
...
2019-11-30 480
2019-12-31 480
2020-01-31 480
  1. 找出每个组的索引日期。
[In] 
resampled_groups = df.set_index("date").resample("M").groups
df_groups = pd.DataFrame(resampled_groups, index=["group"]).T.shift(1)
print(df_groups)
[Out]
2017-12-31 Nan
2018-01-31 1
2018-02-28 1
...
2018-12-31 1
2019-01-31 2
...
2019-04-30 3
2019-05-31 4
2019-06-30 5
2019-07-31 6
2019-08-31 6
2019-09-30 6
2019-10-31 7
...
  1. 计算每组中的出现次数
[In]
s = df_groups.groupby("group").size()
s.name = "count"
s_counts = df_groups.join(s, on="group")["count"]
print(s_counts)
[Out]
2017-12-31 Nan
2018-01-31 12
2018-02-28 12
...
2018-12-31 12
2019-01-31 3
...
2019-04-30 1
2019-05-31 1
2019-06-30 1
2019-07-31 3
2019-08-31 3
2019-09-30 3
2019-10-31 4
  1. 将回填值与计数相除。
[In]
res = res.join(s_counts)
res["final_value"] = res["value"]/res["count"]
print(res)
[Out]
date       value count final_value
2017-12-31 600   NaN    NaN
2018-01-31 1200  12     100
2018-02-28 1200  12     100
...
2018-12-31 1200  12     100
2019-01-31 330   3      110
...
2019-04-30 125   1      125
2019-05-31 126   1      126
2019-06-30 127   1      127
2019-07-31 360   3      120
2019-08-31 360   3      120
2019-09-30 360   3      120
2019-10-31 480   4      120
...
2020-01-31 480   4      120
© www.soinside.com 2019 - 2024. All rights reserved.