如何在多索引 pandas 数据帧上将数据滞后x特定天数? [英] How to lag data by x specific days on a multi index pandas dataframe?
问题描述
我有一个数据框,其中包含日期,资产,然后是价格/成交量数据.我正尝试从7天前提取数据,但是问题是我不能使用shift(),因为我的表中缺少日期.
I have a dataframe that has dates, assets, and then price/volume data. I'm trying to pull in data from 7 days ago, but the issue is that I can't use shift() because my table has missing dates in it.
date cusip price price_7daysago
1/1/2017 a 1
1/1/2017 b 2
1/2/2017 a 1.2
1/2/2017 b 2.3
1/8/2017 a 1.1 1
1/8/2017 b 2.2 2
我尝试创建一个lambda函数来尝试使用loc和timedelta来创建此移位,但是我只能输出空的numpy数组:
I've tried creating a lambda function to try to use loc and timedelta to create this shifting, but I was only able to output empty numpy arrays:
def row_delta(x, df, days, colname):
if datetime.strptime(x['recorddate'], '%Y%m%d') - timedelta(days) in [datetime.strptime(x,'%Y%m%d') for x in df['recorddate'].unique().tolist()]:
return df.loc[(df['recorddate_date'] == df['recorddate_date'] - timedelta(days)) & (df['cusip'] == x['cusip']) ,colname]
else:
return 'nothing'
我还考虑过要做与此类似的操作缺少日期,但是我的问题是我有多个索引,日期和临时表,所以我不能只是为此重新索引.
I also thought of doing something similar to this in order to fill in missing dates, but my issue is that I have multiple indexes, the dates and the cusips so I can't just reindex on this.
我不确定我还能做什么,但是任何帮助将不胜感激!
I'm not really sure what else I can do, but any help would be greatly appreciated!
推荐答案
merge
DataFrame
与其自身,同时在右侧Frame的日期列中添加7天.使用后缀
参数适当地命名列.
merge
the DataFrame
with itself while adding 7 days to the date column for the right Frame. Use the suffixes
argument to name the columns appropriately.
import pandas as pd
df['date'] = pd.to_datetime(df.date)
df.merge(df.assign(date = df.date+pd.Timedelta(days=7)),
on=['date', 'cusip'],
how='left', suffixes=['', '_7daysago'])
输出: df
date cusip price price_7daysago
0 2017-01-01 a 1.0 NaN
1 2017-01-01 b 2.0 NaN
2 2017-01-02 a 1.2 NaN
3 2017-01-02 b 2.3 NaN
4 2017-01-08 a 1.1 1.0
5 2017-01-08 b 2.2 2.0
这篇关于如何在多索引 pandas 数据帧上将数据滞后x特定天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!