从一天中不同时间测量的多年温度记录开始,我想以日平均值的矩形数组结束,每一行代表一年的数据。
数据是这样的
temperature.head()
date
1996-01-01 00:00:00 7.39
1996-01-01 03:00:00 6.60
1996-01-01 06:00:00 7.39
1996-01-01 09:00:00 9.50
1996-01-01 12:00:00 11.00
Name: temperature, dtype: float64
我计算了每日平均值
import pandas as pd
daily = temperature.groupby(pd.TimeGrouper(freq='D')).mean()
哪个产量
daily.head()
date
1996-01-01 9.89625
1996-01-02 10.73625
1996-01-03 6.98500
1996-01-04 5.62250
1996-01-05 8.84625
Freq: D, Name: temperature, dtype: float64
现在对于最后一部分,我想到了类似的东西
yearly_daily_mean = daily.groupby(pd.TimeGrouper(freq='12M', closed="left"))
但是这里有一些问题。
- 我需要删除未填满整整一年的数据尾部。
- 如果缺少数据会怎样?
- 如何处理闰年?
- 下一步是什么?即,如何“堆叠”(在 numpy 的意义上,而不是 pandas 的意义上)多年的数据?
我正在使用
array_temperature = np.column_stack([group[1] for group in yearly_daily_mean if len(group[1]) == 365])
但应该有更好的方法。
附属问题,如何选择数据年份的起始日?
最佳答案
如果我对你的理解是正确的,你想将每日均值(你已经计算过)的时间序列 reshape 为一个矩形数据框,其中不同的日子作为列,不同的年份作为行。
这可以通过 pandas reshape 功能轻松实现,例如 pivot
:
一些虚拟数据:
In [45]: index = pd.date_range(start=date(1996, 1,1), end=date(2010, 6, 30), freq='D')
In [46]: daily = pd.DataFrame(index=index, data=np.random.random(size=len(index)), columns=['temperature'])
首先,我添加包含年份和年份的列:
In [47]: daily['year'] = daily.index.year
In [48]: daily['day'] = daily.index.dayofyear
In [49]: daily.head()
Out[49]:
temperature year day
1996-01-01 0.081774 1996 1
1996-01-02 0.694968 1996 2
1996-01-03 0.478050 1996 3
1996-01-04 0.123844 1996 4
1996-01-05 0.426150 1996 5
现在,我们可以 reshape 这个数据框:
In [50]: daily.pivot(index='year', columns='day', values='temperature')
Out[50]:
day 1 2 ... 365 366
year ...
1996 0.081774 0.694968 ... 0.679461 0.700833
1997 0.043134 0.981707 ... 0.009357 NaN
1998 0.257077 0.297290 ... 0.701941 NaN
... ... ... ... ... ...
2008 0.047145 0.750354 ... 0.996396 0.761159
2009 0.348667 0.827057 ... 0.881424 NaN
2010 0.269743 0.872655 ... NaN NaN
[15 rows x 366 columns]
关于python - 对齐多年的日常数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951018/