python返回上一行,获取上一行的值并计算新列pandas python

该博客讨论如何在Python Pandas数据帧中,根据特定条件(如相同'case'值)计算当前行与上一行'change'列的差值。通过使用'shift'方法获取上一行的值,然后进行时间戳相减,可以创建新的列来存储这些差异。此方法适用于0.13.1及更高版本的Pandas库。
摘要由CSDN通过智能技术生成

Is there a way to look back to a previous row, and calculate a new variable? so as long as the previous row is the same case what is the (previous change) - (current change), and attribute it to the previous 'ChangeEvent' in new columns?

here is my DataFrame

>>> df

ChangeEvent StartEvent case change open

0 Homeless Homeless 1 2014-03-08 00:00:00 2014-02-08

1 other Homeless 1 2014-04-08 00:00:00 2014-02-08

2 Homeless Homeless 1 2014-05-08 00:00:00 2014-02-08

3 Jail Homeless 1 2014-06-08 00:00:00 2014-02-08

4 Jail Jail 2 2014-06-08 00:00:00 2014-02-08

to add columns

Jail Homeless case

0 6 1

0 30 1

0 0 1

... and so on

here is the df build

import pandas as pd

import datetime as DT

d = {'case' : pd.Series([1,1,1,1,2]),

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值