python - 如何使用 groupby 减去列中的值

标签 python pandas pandas-groupby

我有以下数据框:

ID  Days TreatmentGiven TreatmentNumber
--- ---- -------------- ---------------
1    0      False             NaN
1    30     False             NaN
1    40     True               1
1    56     False             NaN 
2    0      False             NaN
2    14     True               1
2    28     True               2 

我想根据第一次治疗的时间 (TreatmentNumber==1) 创建一个新列,其中包含天数的新基线,并按 ID 分组,以便结果如下:

ID  Days TreatmentGiven TreatmentNumber New_Baseline
--- ---- -------------- --------------- ------------
1    0      False             NaN          -40
1    30     False             NaN          -10
1    40     True               1            0
1    56     False             NaN           16
2    0      False             NaN          -14
2    14     True               1            0
2    28     True               2            14

执行此操作的最佳方法是什么?

谢谢。

最佳答案

这是一种使用 series.where + groupby+transform 的方法:

s = df['Days'].where(df['TreatmentGiven']).groupby(df['ID']).transform('first')
df['New_Baseline'] = df['Days'].sub(s)

输出

   ID  Days  TreatmentGiven  TreatmentNumber  New_Baseline
0   1     0           False              NaN         -40.0
1   1    30           False              NaN         -10.0
2   1    40            True              1.0           0.0
3   1    56           False              NaN          16.0
4   2     0           False              NaN         -14.0
5   2    14            True              1.0           0.0
6   2    28            True              2.0          14.0

关于python - 如何使用 groupby 减去列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60618799/

相关文章:

python - 在 Python 上显示来自 Matlab mat 文件的图像

python - 将默认颜色旋转 matplotlib 更改为特定颜色图

python - 使用 Pandas 创建日期范围列表

python - 在python中聚合 Pandas 数据时如何计算每组尾部的总和|均值|中位数

python - 使用来自不同数据集的组均值填充一个数据集中的缺失值

python - 如何删除 pandas 中 count 和 sum 为 1 的行

python - 如何将 numpy 数组发送到 Armadillo (C++) 并从 Armadillo 返回一个 numpy 数组

python - 阿拉伯语/波斯语未正确打印到屏幕

python - Pandas read_html 值错误 : No tables found

python - 计算 Pandas 当前行之前的空白数