Sum of first n rows

Suppose I have a column with some values and I want to print only first n rows whose sum is equal to 60 or approximately equal to 60.

output

Thank you.

Next time, I’ll be careful.

Not enough information: this could be from a csv file, or it could be a Pandas DF, or a NumPy array or something else?

Also, what have you tried? If you post some code (formatted) that would, at the least, clue us all in.

I have extracted this one column from pandas dataframe.

Again, some code would help: have you stored the extracted numbers as a DF, or something else?

To add: Possibly, the easiest code to write, would be to extract the numbers into a Python list, then loop through said list, adding each number to a new list as well as keeping a running total of used numbers. Terminate the loop when the total value > 60, then do whatever you need to do with the resulting data.

You could even do that in the extraction loop, rather than extracting every number; simply stop the extraction loop when the total value > 60

Yes, saved into a new dataframe (df_new).
I also thought of iterating through all the rows but I don’t know how to execute it. Tbh my looping concept is very weak. I will be extremely grateful if you tell me how to do it.

I’m sure you can code something, if you try. To have tried and failed is better than not trying at all. There are many, many, many examples (including your own threads) posted in this Forum that demonstrate the principles of this concept. If you never try to code these things, you’ll never learn.

1 Like

I know very little about pandas and dataframes, but have you tried to search for existing answers?

As I said, I’m not much of a pandas coder, but have you tried:

# Untested.
for row in df:
    print(row)

for example? That might give you a hint how to proceed. If you copy and paste the output and show us, it might give us a hint as well.

column_sum = 0
row_count = 0

for value in df['A']:
    column_sum += value
    row_count += 1
    if 59 <= column_sum <= 61:
        break

Thank you for motivating guys!

1 Like

Nice one.

So, if the goal is (as per your first post) “print only first n rows whose sum is equal to 60 or approximately equal to 60.”, all you need to do is:

...
for value in df['A']:
    if column_sum < 60: # or whatever your criteria is
        print(value)
        column_sum += value
    else:
        break

A nicer way to count the number of rows would be:

...
for count, value in enumerate(df["A"], 1): # without the 1, the count would start at zero
    if column_sum < 60: # or whatever your criteria is
        print(count, value)
        column_sum += value
    else:
        break

Note: above code has not been tested.

And this time? How about replacing the image with text? Or do you not want help with this anymore?