首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计算从条件标记的子集行到标记的子集行下的其余行的变化率

计算从条件标记的子集行到标记的子集行下的其余行的变化率
EN

Stack Overflow用户
提问于 2020-08-18 08:42:53
回答 1查看 48关注 0票数 4

我有一个数据框架:

代码语言:javascript
运行
复制
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'])

我需要计算每一行与其标记为Truelatest行(不包括标记行本身)之间的score(x - y)/y的更改率。

在前面的示例中,期望的输出应为:

代码语言:javascript
运行
复制
>>> 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

有没有一种简单明了的方法可以做到这一点?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-18 08:55:39

在这里,我们首先需要使用cumsum创建groupby密钥,对于每个子组,我们需要按组创建值

代码语言:javascript
运行
复制
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的值作为每个组的移位值

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63460349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档