Skip to main content
 首页 » 编程设计

python之pd.Series/DataFrame 中每周的第一个值

2024年10月01日6insus

假设我有一个 pd.Series daily 标准普尔 500 值,我想过滤这个系列以获得第一个工作日和每周的相关值。

因此,例如,我过滤的系列将包含 2017 年 9 月 5 日(星期二 - 星期一没有值),然后是 2017 年 9 月 11 日(星期一)。

Source series:  
2017-09-01    2476.55 
2017-09-05    2457.85 
2017-09-06    2465.54 
2017-09-07    2465.10 
2017-09-08    2461.43 
2017-09-11    2488.11 
2017-09-12    2496.48 
 
Filtered series 
2017-09-01    2476.55 
2017-09-05    2457.85 
2017-09-11    2488.11 

我的解决方案目前包括:

mask     = SP500.apply(lambda row: SP500[row.name - datetime.timedelta(days=row.name.weekday()):].index[0], axis=1).unique() 
filtered = SP500.loc[mask] 

然而,这感觉不太理想/非 Pythonic。任何更好/更快/更清洁的解决方案?

请您参考如下方法:

在pd.Series.index.to_series上使用resample

s[s.index.to_series().resample('W').first()] 
 
2017-09-01    2476.55 
2017-09-05    2457.85 
2017-09-11    2488.11 
dtype: float64