1

I need to modify my code:

db_profit_platform=db[['Source','Device','Country','Profit']]
db_profit_final=db_profit_platform.groupby(['Source','Device','Country'])['Profit'].apply(sum).reset_index()

Now I need to add Bid and get average bid after group by (different aggregations for different columns): to get: Source Device Country SumProfit Average Bid

How can I do it? (and maybe I will need more aggregations) Thanks

Costa
  • 51
  • 2

1 Answers1

1

You can use agg function, here a minimal working example

import numpy as np
import pandas as pd

size = 10

db = pd.DataFrame({
    'Source': np.random.randint(1, 3, size=size),
    'Device': np.random.randint(1, 3, size=size),
    'Country': np.random.randint(1, 3, size=size),
    'Profit': np.random.randn(size),
    'Bid': np.random.randn(size)
})

db.groupby(["Source", "Device", "Country"]).agg(
    sum_profit=("Profit", "sum"),
    avg_bid=("Bid", "mean")
)

See the official documentation https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.agg.html as well as this question

Andrea Di Iura
  • 467
  • 5
  • 11