python - summing values by rank in pandas -


i trying multi-year financial forecast. need calculate spending based on rank year , re-rank , calculate spending next year.

my data frame has car parts , cost fix/replace constrained budget (400 dollars) once budget spent can no longer fix else year re prioritized following year.

in year 1, budget covers transmission, in year 2 transmission fine , ranked lowest. how can run cumulative sum based on rank until budget limit?

   df    part           rank(year 1)     cost(y1)   spend(y1)   rank(y2)   spend(y2)     transmission        1               400       400         4          0    tires               2               400        0          1         400    windshield          3               100        0          2          0    wipers              4                20        0          3          0 

also want add:

    val in df['spend']:         if val.cumsum() >= budget_var:           val = 0 

this how right need sum in order of rank.

sorted_df = df.sort_values(col_name) 

also, don't think cumsum() right; you're applying individual values in column, rather column whole.

try this

df['spend'] = max(0,df['cost'].cumsum()) 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -