Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many rows are needed to add up to a value

Tags:

python

pandas

I have a Dataframe

Acc_Name       gb
ABC            76
DEF            67
XYZ            50
RES            43
FEG            22 
HTE            0
DGE            0 

The sum of GB column is 258 and its 80% is 206.4

I want the count, how many rows if summed from top are less than or equal to the value 206.4 in the DataFrame.

Manually if I check I get the first 3 rows as answer, but how to get that using Pandas.


1 Answers

You want cumsum for this:

df.gb.cumsum().lt(206.4).sum()
# 3

To do it all in one go:

df['gb'].cumsum().div(df['gb'].sum()).le(0.8).sum()
# 3
like image 169
yatu Avatar answered Nov 21 '25 23:11

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!