达到阈值后将累积值设置为常数

编程入门 行业动态 更新时间:2024-10-09 05:16:00
本文介绍了达到阈值后将累积值设置为常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个熊猫时间序列,其中包含每月的累积值.

I have a pandas time series which contains cumulative monthly values.

如果在某个日期的一个月中,该值变为某个数字,我需要将其余日子设置为1000.

If in a month on a certain date, the value becomes a certain number, I need to set rest of the days to 1000.

例如

df: Date cummulative_value 1/8/2017 -3 1/9/2017 -6 1/10/2017 -72 1/11/2017 500 1/26/2017 575 2/7/2017 -5 2/14/2017 -6 2/21/2017 -6

我的截止值是-71,所以在上面的示例中,我需要实现以下目标:

My cutoff value is -71 so in above example I need to achieve the following:

Date cummulative_value 1/8/2017 -3 1/9/2017 -6 1/10/2017 1000 1/11/2017 1000 1/26/2017 1000 2/7/2017 -5 2/14/2017 -6 2/21/2017 -6

我正在尝试在熊猫中利用groupby,但是我不确定该怎么做.任何其他更有效的方法也会有所帮助.

I am trying to leverage groupby in pandas but I am not sure how to go about it. Any other more efficient way will help also.

推荐答案

使用groupby和cumprod:

df['cummulative_value'] = (df.groupby(df['Date'].dt.strftime('%Y%m'))['cummulative_value'] .transform(lambda x: np.where(x.ge(-71).cumprod(),x,1000))) print(df)

输出:

Date cummulative_value 0 2017-01-08 -3 1 2017-01-09 -6 2 2017-01-10 1000 3 2017-01-11 1000 4 2017-01-26 1000 5 2017-02-07 -5 6 2017-02-14 -6 7 2017-02-21 -6

更多推荐

达到阈值后将累积值设置为常数

本文发布于:2023-10-16 14:10:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497794.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阈值   常数   后将   设置为

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!