如何重新采样到较粗的分辨率但在原始索引内采样?

How to resample to a coarser resolution but to samples within the original index?

我有以下用例:

import pandas as pd
import numpy as np

# create dataframe
df = pd.DataFrame(data=np.random.rand(10, 3),
                  columns=['a', 'b'],
                  index=pd.date_range('2021-01-01', periods=10, freq='W-FRI'))
# data is random, I'm just saving time with copy paste first row
df
>               a          b
> 2021-01-01    0.272628   0.974373
> 2021-01-08    0.272628   0.974373
> 2021-01-15    0.272628   0.974373
> 2021-01-22    0.272628   0.974373
> 2021-01-29    0.272628   0.974373
> 2021-02-05    0.759018   0.443803
> 2021-02-12    0.759018   0.443803
> 2021-02-19    0.759018   0.443803
> 2021-02-26    0.759018   0.443803
> 2021-03-05    0.973900   0.929002

我想在重新采样时获取索引中的第一个匹配样本,但执行以下操作不起作用,请注意日期不在我的原始索引中:

df.resample('M').first()
>               a          b
> 2021-01-31    0.272628   0.160300
> 2021-02-28    0.759018   0.443803
> 2021-03-31    0.973900   0.929002

我想按月重新采样,但每次都取第一个匹配日期样本,即我想要以下结果:

>               a          b
> 2021-01-01    0.272628   0.160300
> 2021-02-05    0.759018   0.443803
> 2021-03-05    0.973900   0.929002

我可以按如下方式进行破解,但这并不理想,它只适用于这个玩具示例:

df.loc[list(np.diff(df.index.month.values, prepend=0) == 1)]

一种方法是将索引转换为句点,然后删除重复项:

months = df.index.to_series().dt.to_period('M')
df[~month.duplicated()]

另一个实际上可能更好的是 groupby().head()

df.groupby(pd.Grouper(freq='M')).head(1)

输出:

                   a         b
2021-01-01  0.695784  0.228550
2021-02-05  0.188707  0.278871
2021-03-05  0.935635  0.785341