How to assign data from pandas groupby function to a variable?

Viewed 29

I have a question regarding Pandas. I grouped data by column (Districts)

GroupByDistrict = df.groupby(['District'])

and then I want to get data

print(GroupByDistrict['Price'].agg(['median','mean']))

Output of this command shows average prices in different districts.
How can I assign this data to a variable (list or dictionary)?

If I do something like this

xx = GroupByDistrict['Price'].agg(['median','mean']) 
print(xx)

the output gives object

1 Answers

You can do that as:

district_prices = df.groupby('District').agg({'Price': [ 'median', 'mean']}).apply(list).to_dict()

print(district_prices)
Related