【发布时间】:2021-08-21 15:57:12
【问题描述】:
我有一些从 2003 年到 2011 年的分层数据,这些数据最终形成时间序列数据,看起来像这样:
polar_temp
Station_Number Date Value
417 CA002100805 20030101 -296
423 CA002202570 20030101 -269
425 CA002203058 20030101 -268
427 CA002300551 20030101 -23
428 CA002300902 20030101 -200
我在 Station_Number 和 Date 上设置了多重索引:
polar_temp['Date'] = pd.to_datetime(polar_temp['Date'],
format='%Y%m%d')#.dt.strftime("%Y-%m-%d")
polar_temp = polar_temp.set_index(['Station_Number', "Date"])
Value
Station_Number Date
CA002100805 2003-01-01 -296
CA002202570 2003-01-01 -269
CA002203058 2003-01-01 -268
CA002300551 2003-01-01 -23
CA002300902 2003-01-01 -200
现在我想通过使用以下方法计算每 8 天的 Value 的平均值来对数据进行重新采样:
polar_temp8d = polar_temp.groupby([pd.Grouper(level='Station_Number'),
pd.Grouper(level='Date', freq='8D')]).mean()
Value
Station_Number Date
CA002100805 2003-01-01 -300.285714
2003-01-09 -328.750000
2003-01-17 -325.500000
2003-01-25 -385.833333
2003-02-02 -194.428571
... ...
USW00027515 2005-06-23 76.625000
2005-07-01 42.375000
2005-07-09 94.500000
2005-07-17 66.500000
2005-07-25 56.285714
所以这里的问题是 pandas 只对 2003 年到 2005 年的年份进行重新采样,所以 2006 年到 2011 年的年份完全被忽略了。现在我的问题是:我是使用 Grouper 函数正确分析时间序列数据还是我遗漏了什么?
编辑 1:
通过运行:
print(polar_temp.loc['CA002300902'].sort_index(ascending=False))
Value
Date
2011-12-31 -288
2011-12-30 -299
2011-12-29 -347
2011-12-28 -310
2011-12-27 -239
可以看到重采样前的台站有到2011年的数据。
【问题讨论】:
-
某些台站2005年以后没有数据吗?我相信汇总只会包括有车站数据的时期。
-
但是对于有 2003 年到 2011 年数据的站点,聚合仍然应该运行,因为据我了解,pandas 会明智地运行重采样站。
-
您能否通过运行
df.loc[STATION_WITH_LATER_DATA'].sort_index(ascending=False)再次检查。另外,我认为这不会产生影响,但polar_temp.groupby(['Station Number', pd.Grouper(level='Date', freq='8D')])足以进行分组操作。 -
感谢您要求我仔细检查,因为对于某些站点,重新采样在整个时间段内都有效,但是行数下降到 60.000 左右,而应该在 300.000 左右
-
我又检查了一遍,甚至有几年的数据空白,这不可能是真的。
标签: python pandas time-series multi-index