简体   繁体   English

Pandas数据帧按日期移动列

[英]Pandas dataframe shift column by date

I have a panel dataset which is indexed by Date and ID and looks something like this: 我有一个面板数据集,它按日期和ID索引,看起来像这样:

df = pd.DataFrame({'Date':['2005-12-31', '2006-03-31', '2006-09-30','2005-12-31', '2006-03-31', '2006-06-30', '2006-09-30'],
              'ID':[1,1,1,2,2,2,2],
              'Value':[14,25,34,23,67,14,46]})

I'm trying to shift the values of the same ID by Date and Date can be non-continuous quarters. 我试图按日期和日期移动相同ID的值可以是非连续的季度。 groupby.shift doesn't give me the right thing or maybe I'm missing something. groupby.shift没有给我正确的东西,也许我错过了什么。 Here is what I did: 这是我做的:

df['pre_value'] = df.groupby('ID')['Value'].shift(1)

This does shift values of the same ID, but it ignores the date... note that for ID==1 , the 2006-06-30 is missing and therefore the pre_value for its 2006-09-30 should really be NaN. 这确实转移了相同的ID值,但它忽略了日期...注意, ID==1 ,在2006-06-30丢失,因此pre_value2006-09-30确实应该为NaN。 I'm also looking into multiindexing or declaring the dataset as panel, but that complicates my other calculations. 我也在研究多索引或将数据集声明为面板,但这使我的其他计算变得复杂。 Is there any easy way to do this with dataframe? 有没有简单的方法来使用dataframe?

I would just make a copy of the dataframe, shift Date by 1 (seems you want shift by a quarter), and then merge back to the original dataframe. 我只是复制数据帧,将Date移位1(似乎你想要移动四分之一),然后合并回原始数据帧。 To shift date, you can convert string dates to pandas period so shifting will be easier. 要转换日期,您可以将字符串日期转换为pandas时段,以便更轻松地进行转换。

In [34]: df['Date'] = pd.PeriodIndex(df['Date'], freq='Q')

In [35]: df2 = df.copy()

In [36]: df2['Date'] += 1

In [37]: df.merge(df2, on=['Date','ID'], suffixes=('', '_lag1'), how='left')
Out[37]:
    Date  ID  Value  Value_lag1
0 2005Q4   1     14         NaN
1 2006Q1   1     25          14
2 2006Q3   1     34         NaN
3 2005Q4   2     23         NaN
4 2006Q1   2     67          23
5 2006Q2   2     14          67
6 2006Q3   2     46          14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM