I got a dataframe like this:
data = {
'YEAR' : [2018,2018,2017,2018,2018,2018],
'SEASON': ['SPRING', 'SPRING', 'WINTER', 'SPRING', 'SPRING', 'SPRING'],
'CODE': ['A', 'A', 'A', 'B', 'C', 'D'],
'BUDGET': [500,200,300,4000,700,0],
'QUANTITY': [1000,1000,1000,2000,300,4000]
}
df = pd.DataFrame(data)
'''
BUDGET CODE QUANTITY SEASON YEAR
0 500 A 1000 SPRING 2018
1 200 A 1000 SPRING 2018
2 300 A 1000 WINTER 2017
3 4000 B 2000 SPRING 2018
4 700 C 300 SPRING 2018
5 0 D 4000 SPRING 2018
'''
For each CODE I got its correct BUDGET quantity, but unfortunately on the QUANTITY column I got the total quantity for that code within every [Year, Season].
I'm working on a function to aggregate my dataframe at different levels given as input: for example I'm giving the function a list like
my_list = [
['YEAR']
['YEAR', 'SEASON']
]
and the function will output a series of dataframes grouped by each sublist.
The problem here is I can aggregate CODE with pd.Series.nunique and I can sum the BUDGET column, but if I sum also the QUANTITY column I will obviously sum up more than I want. What I would need is some sort of sumUniques function by uniques YEAR, SEASON, CODE.
def sumUniques(x):
return '???'
print(df.groupby(['YEAR', 'SEASON']).agg({
'CODE': pd.Series.nunique,
'BUDGET': sum,
'QUANTITY' : sumUniques
}))
'''
CODE BUDGET QUANTITY
YEAR SEASON
2017 WINTER 1 300 ???
2018 SPRING 4 5400 ???
--> EXPECTED RESULT:
CODE BUDGET QUANTITY
YEAR SEASON
2017 WINTER 1 300 1000
2018 SPRING 4 5400 7300
'''
I'm asking myself which could be the best way to achieve this and I came upon Zero's answer to "Pandas: sum values from column to unique values": I've tried it out, by it seems like either I'm not applying it correctly or that does not apply my problem, as it raises a key error:
print(df.groupby(['YEAR', 'SEASON']).agg({
'CODE': pd.Series.nunique,
'BUDGET': sum,
'QUANTITY' : lambda x: x.groupby('CODE').QUANTITY.first().sum()
}))
'''
KeyError: 'CODE'
'''
I wonder what's the best way to make this work, hope this will be of help for others too!