我的Dataframe具有以下结构:
patient_id | timestamp | measurement
A | 2014-10-10 | 5.7
A | 2014-10-11 | 6.3
B | 2014-10-11 | 6.1
B | 2014-10-10 | 4.1
我想计算每位患者每次测量之间的delta
(差异)。
结果如下:
patient_id | timestamp | measurement | delta
A | 2014-10-10 | 5.7 | NaN
A | 2014-10-11 | 6.3 | 0.6
B | 2014-10-11 | 6.1 | 2.0
B | 2014-10-10 | 4.1 | NaN
如何在熊猫中最优雅地完成这项工作?
答案 0 :(得分:2)
在'measurement'列上调用transform
并传递方法diff
,transform会返回一个索引与原始df对齐的系列:
In [4]:
df['delta'] = df.groupby('patient_id')['measurement'].transform(pd.Series.diff)
df
Out[4]:
patient_id timestamp measurement delta
0 A 2014-10-10 5.7 NaN
1 A 2014-10-11 6.3 0.6
2 B 2014-10-10 4.1 NaN
3 B 2014-10-11 6.1 2.0
修改强>
如果您打算对transform
的结果应用某些排序,请先对df进行排序:
In [10]:
df['delta'] = df.sort(columns=['patient_id', 'timestamp']).groupby('patient_id')['measurement'].transform(pd.Series.diff)
df
Out[10]:
patient_id timestamp measurement delta
0 A 2014-10-10 5.7 NaN
1 A 2014-10-11 6.3 0.6
2 B 2014-10-11 6.1 2.0
3 B 2014-10-10 4.1 NaN