本文介绍了达到阈值后将累积值设置为常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫时间序列,其中包含每月的累积值.
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更多推荐
达到阈值后将累积值设置为常数
发布评论