'How to use groupBy in Pandas to sum total revenue of a customer [duplicate]
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:
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.
Solution 1:[1]
You can aggregate the results by using groupby function.
df.groupby('id').agg({'revenue':'sum'})
Solution 2:[2]
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'})
Solution 3:[3]
import pandas as pd
group_df = pd.DataFrame(data=[
['MI','P1','Male',54,15],
['MI','P2','Female',21,19],
['DD','P3','Male',69,26],
['RR','P4','Female',96,28],
['GT','P5','Male',33,24],
['MI','P6','Female',51,33],
['KNR','P7','Male',24,40],
['GT','P8','Male',36,42],
['RR','P9','Female',78,19],
['KNR','P10','Male',33,17],
['MI','P11','Female',87,20],
['GT','P12','Male',81,21],
['KNR','P13','Female',36,29]],
columns=['Team','Player','Sex','Score','Age'])
group_arg = group_df.groupby('Team')
# Returns a dataframe for Team 'MI'
group_arg.get_group('MI')
Solution 4:[4]
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()
Solution 5:[5]
You can use pandas group by function and pass customers and revenue columns
df = df.groupby("customer")["revenue"].sum()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aniruddha |
| Solution 2 | user7375116 |
| Solution 3 | Niket Nishi |
| Solution 4 | Elli |
| Solution 5 | Arun Kumar |

