pandas :从一年中的同一天的前一年获取价值 [英] Pandas: get a value from previous year for the same day of the year

查看:90
本文介绍了 pandas :从一年中的同一天的前一年获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种如何在同一天从上一年获得价值的方法.

I'm looking for a way how to get a value from the previous year for the same day.

F.e.我们有一个2014年1月1日的值,我想用这一天但一年前的值创建一个新列.

F.e. we have a value for 2014-01-01 and I want to create a new column with the value for this day but from one year ago.

表的样本,我想获取Previos_Year列.

a sample of the table, and I want to get the Previos_Year column.

   Date   Ticks Previos_Year 
2013-01-01  0        NaN
2013-01-02  1        NaN
2013-01-03  2        NaN
....
2014-01-01  3         0
2014-01-02  4         1

到目前为止我尝试过什么:

What have I tried so far:

我创建了一年中的新列日,

I created a new column day of the year,

df['Day_in_Year'] = df.Date.dt.dayofyear

但是我不知道如何在任务中使用它.

but I could not figure out how to use it for my task.

我还尝试了换档功能:

df['Ticks'].shift(365)

它有效,直到a年...

and it works, until a leap year...

推荐答案

您可以groupby月和日,然后shift

df['Previous'] = df.groupby([df['Date'].dt.month,df['Date'].dt.day])['Value'].shift()

样本输出:

        Date  Ticks  Value  Previous
0 2013-01-01      0     99       NaN
1 2013-01-02      1      0       NaN
2 2013-01-03      2      5       NaN
3 2014-01-01      3      0      99.0
4 2014-01-02      4      1       0.0
5 2014-01-03      2      5       5.0
7 2014-01-04      2      5       NaN

这篇关于 pandas :从一年中的同一天的前一年获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆