pandas 中的多年重采样

Resampling for multiple years in pandas

我有多年所有天数的数据(从 2004 年到 2014 年的 10 年期间)。我想找到 10 年中所有天的这段时间的最大值和最小值,例如。 2004 年到 2014 年之间所有年份的 1 月 1 日的最大值是多少。我将如何使用 pandas 中的重新采样来做到这一点? Refer to this image

使用:

rng = pd.date_range('2004-01-01', '2014-12-31')
df = pd.DataFrame({'Date': rng, 'Max': range(len(rng))})  
print (df)
           Date   Max
0    2004-01-01     0
1    2004-01-02     1
2    2004-01-03     2
3    2004-01-04     3
4    2004-01-05     4
        ...   ...
4013 2014-12-27  4013
4014 2014-12-28  4014
4015 2014-12-29  4015
4016 2014-12-30  4016
4017 2014-12-31  4017

[4018 rows x 2 columns]

首先通过 to_datetime, then create custom format MM-DD by Series.dt.strftime 将列 Date 转换为日期时间,最后聚合 max:

df['Date'] = pd.to_datetime(df['Date'])
#if necessary sorting
#df = df.sort_values('Date')
md = df['Date'].dt.strftime('%b-%d')
df = df.groupby(md, sort=False)['Max'].max().reset_index()
print (df)
       Date   Max
0    Jan-01  3653
1    Jan-02  3654
2    Jan-03  3655
3    Jan-04  3656
4    Jan-05  3657
..      ...   ...
361  Dec-27  4013
362  Dec-28  4014
363  Dec-29  4015
364  Dec-30  4016
365  Dec-31  4017

[366 rows x 2 columns]

如果您想将原始日期关联到最大值和最小值(基于 question),我建议这样做:

import pandas as pd
import numpy as np
np.random.seed(13)
df = pd.DataFrame({"date":pd.date_range("2004-01-01", freq="D", periods=5000),
                   "value": np.random.randint(0,100,5000)})
df["day"] = df.date.dt.day
df["month"] = df.date.dt.month
df = df.set_index("date")
idx = df.groupby(['month', 'day'])['value'].transform(max) == df['value']
max_df = df[idx].sort_values(["month", "day"])
idx = df.groupby(['month', 'day'])['value'].transform(min) == df['value']
min_df = df[idx].sort_values(["month", "day"])

结果例如 max_df :

           value  day  month
date                         
2010-01-01     88    1      1
2008-01-02     88    2      1
2011-01-03     94    3      1
2009-01-04     98    4      1
2004-01-05     98    5      1

如果有多个最大值,同一天和同一月可以有多行。