Skip to content
Advertisement

Sum rows based on columns inside pandas dataframe

I am quite new to pandas, but I use python at a good level.

I have a pandas dataframe which is organized as follows

JavaScript

It is a fairly large dataframe (7 columns and ~600k rows).

What I would like to do is: given a tuple containing values referring to the idbasin column (e.g. (1,2)), if the idrun value is the same

  1. sum the q column of the referred idbasin values, i.e. for the example it would be (1,2)
  2. remove the rows corresponding to that idrun value and the tuple-specified idbasin values
  3. insert the summed values with idbasin equal to the first number of the tuple.

Referring to my example df, the results would be

JavaScript

My solution would to use groupby to turn the df to a dict and then do the operation with one or two for loops, but I understand that iterating in pandas is not the optimal solution, so I believe there could be a “pandas” solution using the df.

Advertisement

Answer

You can replace values of tuple by first value of tuple in Series.mask and then aggregate sum:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement