熊猫-根据列中的先前值设置值

时间:2020-06-23 06:08:38

标签: python-3.x pandas shift

我有一个包含降雨数据的数据集。我想使用熊猫来设置雨水收集器。

这就是我所拥有的:

def determinePrev(df):
    #NEED TO CHANGE VALUE TO RUNNING     VVVVVV#    
    df.loc[df['Rain'] > 0, 'Running']=df['Rain'].shift(1)+df['Rain']

    return df

像这样运行它,但是仅当连续下两天下雨时才合适。当用“运行”替换后一个“雨”之一时,出现KeyError:“运行”。

我一直在寻找解决方案,但是感觉好像什么都没得到。我对Python来说还比较陌生,所以如果您有解决方案,能否请您提供更多详细信息?

谢谢!

编辑:我应该补充一点,我不想计算连续的天数,而是测量连续的雨天中的降雨量。

编辑#2:

Picture of current output versus desired output

1 个答案:

答案 0 :(得分:0)

使用Series.eqSeries.cumsum来计算累积序列c,该累积序列用于对连续的雨天进行分组,然后使用Series.groupby对{{1} }本系列的}列,并使用转换函数Rain

cumsum

结果:

c = df['Rain'].eq(0).cumsum()
df['Running'] = df['Rain'].groupby(c).cumsum()