get previous row's value and calculate new column pandas python

get previous row's value and calculate new column pandas python,第1张

get previous row's value and calculate new column pandas python

The way to get the previous is using the shift method:

In [11]: df1.change.shift(1)Out[11]:0          NaT1   2014-03-082   2014-04-083   2014-05-084   2014-06-08Name: change, dtype: datetime64[ns]

Now you can subtract these columns. Note: This is with 0.13.1 (datetime stuff
has had a lot of work recently, so YMMV with older versions).

In [12]: df1.change.shift(1) - df1.changeOut[12]:0        NaT1   -31 days2   -30 days3   -31 days4     0 daysName: change, dtype: timedelta64[ns]

You can just apply this to each case/group:

In [13]: df.groupby('case')['change'].apply(lambda x: x.shift(1) - x)Out[13]:0        NaT1   -31 days2   -30 days3   -31 days4        NaTdtype: timedelta64[ns]


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5668311.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存