gpt4 book ai didi

python-3.x - 在 Python Pandas 中,将 cumsum 与 groupby 结合使用,并在值为 0 时重置 cumsum

转载 作者:行者123 更新时间:2023-12-02 12:42:31 24 4
gpt4 key购买 nike

我对 python 还很陌生。我尝试对每个客户进行累积总和,以查看相应的不活动月份(标志:1 或 0)。因此,当我们有 0 时,需要重置 1 的累积和。当我们有新客户端时,也需要重置。请参阅下面的示例,其中 a 是客户列,b 是日期。

经过一些研究,我发现了问题“Cumsum Reset at NaN”和“In Python Pandas using cumsum with groupby”。我认为我需要将它们放在一起。将“Cumsum Reset at NaN”的代码调整为重置为0,成功:

cumsum = v.cumsum().fillna(method='pad')
reset = -cumsum[v.isnull() !=0].diff().fillna(cumsum)
result = v.where(v.notnull(), reset).cumsum()

但是,我没有成功添加 groupby。我的计数还在继续......

因此,数据集将如下所示:将 pandas 导入为 pd

df =  pd.DataFrame({'a' : [1,1,1,1,1,1,1,2,2,2,2,2,2,2], 
'b' : [1/15,2/15,3/15,4/15,5/15,6/15,1/15,2/15,3/15,4/15,5/15,6/15],
'c' : [1,0,1,0,1,1,0,1,1,0,1,1,1,1]})

这应该会产生一个包含 a、b、c 和 d 列的数据框,并带有

'd' : [1,0,1,0,1,2,0,1,2,0,1,2,3,4]

请注意,我有一个非常大的数据集,因此计算时间非常重要。

谢谢你帮助我

最佳答案

使用groupby.applycumsum在组中找到连续值之后。然后groupby.cumcount获取每个连续值的整数,然后加 1。

与原始行相乘以创建 AND 逻辑,取消所有零并仅考虑正值。

df['d'] = df.groupby('a')['c']                                                            \
.apply(lambda x: x * (x.groupby((x != x.shift()).cumsum()).cumcount() + 1))

print(df['d'])

0 1
1 0
2 1
3 0
4 1
5 2
6 0
7 1
8 2
9 0
10 1
11 2
12 3
13 4
Name: d, dtype: int64
<小时/>

另一种方法是在 series.expanding 之后应用函数在 groupby 对象上,该对象基本上计算从第一个索引到当前索引的系列上的值。

稍后使用reduce将两个args的函数累积应用到iterable的项上,从而将其减少到单个值。

from functools import reduce

df.groupby('a')['c'].expanding() \
.apply(lambda i: reduce(lambda x, y: x+1 if y==1 else 0, i, 0))

a
1 0 1.0
1 0.0
2 1.0
3 0.0
4 1.0
5 2.0
6 0.0
2 7 1.0
8 2.0
9 0.0
10 1.0
11 2.0
12 3.0
13 4.0
Name: c, dtype: float64

时间:

%%timeit
df.groupby('a')['c'].apply(lambda x: x * (x.groupby((x != x.shift()).cumsum()).cumcount() + 1))
100 loops, best of 3: 3.35 ms per loop

%%timeit
df.groupby('a')['c'].expanding().apply(lambda s: reduce(lambda x, y: x+1 if y==1 else 0, s, 0))
1000 loops, best of 3: 1.63 ms per loop

关于python-3.x - 在 Python Pandas 中,将 cumsum 与 groupby 结合使用,并在值为 0 时重置 cumsum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39741136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com