首页 > 解决方案 > 从 pandas df 中选择并计算特定值

问题描述

我需要一些帮助来解决以下问题:

数据看起来像

dt  value
15  0
15  2   
15  8   
15  8   
15  10  
16  12
15  19  
15  35  
15  45
16  45  
16  45  
15  50
15  0
16  26  
15  43
15  50  
15  0
.
.
.

现在我必须总结 dt 直到值达到 50,总是从 0 开始。

我尝试了以下方法,但我不确定它是否正确,

df['value'].values[(df['value'].values > 0) & (df['value'].values < 50)] = 1    
df =  df.assign(counter_col_x = df.loc[df['value'].eq(1)].groupby(df['value'].ne(df['value'].shift()).cumsum()).ngroup())

感谢您的任何提示!

标签: pythonpandasselectcount

解决方案


如果您不必在一个列中重新启动多次,一种简单的方法是对一个系列进行累积总和。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html

我希望您的意思是值的累积总和,直到达到 50。我只能想出一种在循环中分配 Series 值的方法。希望有帮助。

new_cum_sum = 0
list_of_values = []
for x, y in zip(test['dt'], test['value']):
    if y== 0:
        new_cum_sum = x
    elif y <= 50:
        new_cum_sum+=x
    list_of_values.append(new_cum_sum)

test['test_cum'] = list_of_values

推荐阅读