Home > Mobile >  ***PYTHON*** How to use groupBy in Pandas to sum total revenue of a customer
***PYTHON*** How to use groupBy in Pandas to sum total revenue of a customer

Time:04-08

I'm working with a database but I'm having a problem with only one thing

The part I want to show is in the image below

Part of database

This database includes each customer and their respective plan, indicated by the 'plano' column

The 'valor' column and the 'lt_month' column represent, respectively, the subscription value and the customer lifetime (in months)

The last column represents the total revenue the customer has given us.

Remembering that, in this print screen, both lines represent the same customer. So I would like to turn into a single customer with total revenue of 75.

CodePudding user response:

You can aggregate the results using the function groupby and then agg to calculate the sum of the revenue.

df = pd.DataFrame(data={'id': [1, 2, 1], 'revenue': [10, 20, 30]})
agg_df = df.groupby(by=['id']).agg({'revenue': 'sum'})

CodePudding user response:

If I understand you correctly you just need to use groupby. I'm assuming the columns "Cod" identifies the customer, so:

Df.groupby("Cod")["total_revenue"].sum()
  • Related