python - 计算从条件标记的子集行到标记的行下方的其余行的变化率
问题描述
我有一个数据框:
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
率(不包括标记的行本身)。score
latest
True
对于前面的示例,所需的输出应为:
>>> 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
有没有一种干净简单的方法来做到这一点?谢谢!
解决方案
在这里,我们首先需要使用 来创建groupby
键cumsum
,对于每个子组,我们需要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
的值作为每组移动的值
推荐阅读
- php - php/mysql 响应式成像
- python - 使用 Python 线程的可执行文件的高 CPU 负载
- c# - 如何将 Windows.Forms.Checkbox(图像/绘画)覆盖为自定义复选框?
- oracle - Oracle 到 Redshift 查询迁移
- python-3.x - python for循环计算太低效/太长
- javascript - 在 Node 和 webpack 之间共享 babelified ECMAScript 模块
- android - 如何使用像 Sticker View Corner 这样的 XML 绘制一个带有圆端圆角的矩形
- html - Flex-wrap iOS Safari 和 Chrome
- c# - 如何将数据存储在缓存中?
- php - 在 Ubuntu 18.0.4 上出现错误“您的 php 安装似乎缺少 wordpress 所需的 mysql 扩展”。和 PHP 7.2