我有一个数据框架:
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'])我需要计算每一行与其标记为True的latest行(不包括标记行本身)之间的score中(x - y)/y的更改率。
在前面的示例中,期望的输出应为:
>>> 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有没有一种简单明了的方法可以做到这一点?谢谢!
发布于 2020-08-18 08:55:39
在这里,我们首先需要使用cumsum创建groupby密钥,对于每个子组,我们需要按组创建值
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的值作为每个组的移位值
https://stackoverflow.com/questions/63460349
复制相似问题