Python 如何计算事件窗口的索引系列
假设我有一个这样的时间序列:Python 如何计算事件窗口的索引系列,python,pandas,Python,Pandas,假设我有一个这样的时间序列: pd.Series(np.random.rand(20), index=pd.date_range("1990-01-01",periods=20)) 1990-01-01 0.018363 1990-01-02 0.288625 1990-01-03 0.460708 1990-01-04 0.663063 1990-01-05 0.434250 1990-01-06 0.504893 1990-01-07 0.5877
pd.Series(np.random.rand(20), index=pd.date_range("1990-01-01",periods=20))
1990-01-01 0.018363
1990-01-02 0.288625
1990-01-03 0.460708
1990-01-04 0.663063
1990-01-05 0.434250
1990-01-06 0.504893
1990-01-07 0.587743
1990-01-08 0.412223
1990-01-09 0.604656
1990-01-10 0.960338
1990-01-11 0.606765
1990-01-12 0.110480
1990-01-13 0.671683
1990-01-14 0.178488
1990-01-15 0.458074
1990-01-16 0.219303
1990-01-17 0.172665
1990-01-18 0.429534
1990-01-19 0.505891
1990-01-20 0.242567
Freq: D, dtype: float64
假设事件日期为1990-01-05和1990-01-15。我想在事件周围将数据子集为一个长度为(-2,+2)的窗口,但添加了一个列,该列将产生自事件日期(其值为0)的相对天数:
这个问题与我之前的问题相关:利用@jezrael的“熊猫事件研究”中您以前的解决方案:
import numpy as np
import pandas as pd
s = pd.Series(np.random.rand(20), index=pd.date_range("1990-01-01",periods=20))
date1 = pd.to_datetime('1990-01-05')
date2 = pd.to_datetime('1990-01-15')
window = 2
dates = [date1, date2]
s1 = pd.concat([s.loc[date - pd.Timedelta(window, unit='d'):
date + pd.Timedelta(window, unit='d')] for date in dates])
转换为数据帧:
df = s1.to_frame()
df['Offset'] = pd.Series(data=np.arange(-window,window+1).tolist()*len(dates),index=s1.index)
df
你能再澄清一点吗?@ScottBoston我刚刚更新了我的问题。谢谢@那是你的工作吗?
df = s1.to_frame()
df['Offset'] = pd.Series(data=np.arange(-window,window+1).tolist()*len(dates),index=s1.index)
df