首页 > 解决方案 > 计算从条件标记的子集行到标记的行下方的其余行的变化率

问题描述

我有一个数据框:

import pandas as pd

data = {'score':  [1, 2, 4, 7, 11, 16, 22, 29, 37, 46],
        'tag': [False, True, False, False, True, False, True, False, True, False]
       }

df = pd.DataFrame (data, columns = ['score', 'tag'])

我需要计算每行与其标记的行之间的变化(x - y)/y率(不包括标记的行本身)。scorelatestTrue

对于前面的示例,所需的输出应为:

>>> df
   score    tag   rate
0      1  False    NaN  # NaN as no row was tagged True before
1      2   True    NaN  # NaN as no row was tagged True before
2      4  False    1.0  # (4-2)/2
3      7  False    2.5  # (7-2)/2
4     11   True    4.5  # (11-2)/2: 2 is still used as it's 11's last row above tagged as True
5     16  False   0.45  # (16-11)/11
6     22   True    1.0  # (22-11)/11: 11 is still used as it's 22's last row above tagged as True
7     29  False   0.32  # (29-22)/22
8     37   True   0.68  # (37-22)/22: 22 is still used as it's 37's last row above tagged as True
9     46  False   0.24  # (46-37)/37

有没有一种干净简单的方法来做到这一点?谢谢!

标签: pythonpandasdataframe

解决方案


在这里,我们首先需要使用 来创建groupbycumsum,对于每个子组,我们需要shift按组来赋值

s1=df.tag.iloc[::-1].cumsum().iloc[::-1]
s=df.tag.mul(df.score).groupby(s1).max().shift(-1)
df['rate']=(df.score-s1.map(s))/s1.map(s)
df
Out[75]: 
   score    tag      rate
0      1  False       NaN
1      2   True       NaN
2      4  False  1.000000
3      7  False  2.500000
4     11   True  4.500000
5     16  False  0.454545
6     22   True  1.000000
7     29  False  0.318182
8     37   True  0.681818
9     46  False  0.243243

解释 :

第9行本身是一组,第8-7行是一组,第6-5行是一组...,从标签方面,如果我们颠倒顺序做cumsum,我们可以把它们归为一组,那么我们需要找到带有标签True的值作为每组移动的值


推荐阅读