21
有沒有辦法回頭看從前一行,並計算出一個新的變量?所以只要前一行是相同的情況,(以前的變化) - (當前變化)是什麼,並將它歸入新列中的前一個'ChangeEvent'?獲取前行的值,並計算新列熊貓蟒蛇
這裏是我的數據框
>>> 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
添加列
Jail Homeless case
0 6 1
0 30 1
0 0 1
...等等
這裏是DF構建
import pandas as pd
import datetime as DT
d = {'case' : pd.Series([1,1,1,1,2]),
'open' : pd.Series([DT.datetime(2014, 3, 2), DT.datetime(2014, 3, 2),DT.datetime(2014, 3, 2),DT.datetime(2014, 3, 2),DT.datetime(2014, 3, 2)]),
'change' : pd.Series([DT.datetime(2014, 3, 8), DT.datetime(2014, 4, 8),DT.datetime(2014, 5, 8),DT.datetime(2014, 6, 8),DT.datetime(2014, 6, 8)]),
'StartEvent' : pd.Series(['Homeless','Homeless','Homeless','Homeless','Jail']),
'ChangeEvent' : pd.Series(['Homeless','irrelivant','Homeless','Jail','Jail']),
'close' : pd.Series([DT.datetime(2015, 3, 2), DT.datetime(2015, 3, 2),DT.datetime(2015, 3, 2),DT.datetime(2015, 3, 2),DT.datetime(2015, 3, 2)])}
df=pd.DataFrame(d)
你最後一次可以只是:''df.groupby(案例)[ '變'] DIFF() ''(雖然我不認爲''diff''是cython化的,所以速度應該是一樣的 – Jeff
好極了,這正是我所需要的。 –