Skip to main content
 首页 » 编程设计

python之在不更改日期的情况下在 Pandas 中重新采样

2024年10月24日11zhengyun_ustc

假设我使用 pandas 下载每日股票价格数据:

df = web.DataReader('YHOO', 'yahoo', '1/1/2004', '1/31/2004')['Close'] 

我想要每周第一个交易日的收盘价。这通常是星期一,但如果星期一是假期,则会是星期二。

所以我尝试重新采样:

df.resample('W-MON', how='last') 

得到这个:

Date 
2004-01-05    46.900002 
2004-01-12    49.740002 
2004-01-19    48.110001 
2004-01-26    48.160000 
2004-02-02    46.980000 

Pandas 非常巧妙地只给我星期一的数据。但是 2004-01-19 是一个假期,实际上不在 df 中:

Date 
2004-01-02    45.400002 
2004-01-05    46.900002 
... 
2004-01-15    48.090000 
2004-01-16    48.110001 
2004-01-20    47.660000 
2004-01-21    47.380001 
... 

有没有办法让它在星期一或之后从数据框给出每周的第一个日期? (因此,上面的结果,除了用 2004-01-19 替换为 2004-01-20。)

请您参考如下方法:

如果我们选择将缺失的日期(例如 2004-01-19)移回 到重采样时间段内的最后一个日期(例如 2004-01- 16),那么这可以通过不仅对收盘价而且对 Date 本身应用 重采样 来实现:

import pandas as pd 
import pandas.io.data as pdata 
 
df = pdata.get_data_yahoo('YHOO', start='2004-1-1', end='2004-1-31') 
df['Date'] = df.index 
df = df[['Close', 'Date']] 
 
result = df.resample('W-MON', how='last') 
result = result.set_index('Date') 

产量

                Close 
Date                  
2004-01-05  46.900002 
2004-01-12  49.740002 
2004-01-16  48.110001 
2004-01-26  48.160000 
2004-01-30  46.980000 

因为 df 有一个 Date 列,df.resample('W-MON', how='last') 找到每个重采样组中的最后价格和最后日期。


要解决原始问题,将缺少的日期(例如 2004-01-19)替换为 df 中存在的下一个日期,您可以使用

In [343]: df.index.searchsorted(result.index) 
Out[343]: array([ 1,  6, 11, 15, 20]) 

找到 result.index 中的日期将“适合”df.index 的序号索引,以保持排序顺序。这些索引告诉我们 df.index 中的日期在 result.index 中的相应日期:

In [349]: df.iloc[[1,6,11,15]].index 
Out[349]: DatetimeIndex(['2004-01-05', '2004-01-12', '2004-01-20', '2004-01-26'], dtype='datetime64[ns]', name=u'Date', freq=None) 

然后使用这些序号索引将日期从 df.index 重新分配回 result.index:

import pandas as pd 
import pandas.io.data as pdata 
 
df = pdata.get_data_yahoo('YHOO', start='2004-1-1', end='2004-1-31')['Close'] 
 
result = df.resample('W-MON', how='last') 
idx = df.index.searchsorted(result.index) 
# np.clip reduces the index by 1 if a date in result.index comes after all dates in df.index 
idx = np.clip(idx, 0, len(df)-1) 
result.index = df.iloc[idx].index 

产量

Date 
2004-01-05    46.900002 
2004-01-12    49.740002 
2004-01-20    48.110001 
2004-01-26    48.160000 
2004-01-30    46.980000 
Name: Close, dtype: float64 

请注意,最后日期移至 2004-01-30,因为 2004-02-02 也不在 df.index 中df.index 中的最后可用日期是 2004-01-30。