I have a list of dictionaries with the following keys: country, points, price. I need to get an average of points and price for each country. Here is the list:
0: {country: "US", points: 96, price: 235}
1: {country: "Spain", points: 96, price: 110}
2: {country: "US", points: 96, price: 90}
3: {country: "US", points: 96, price: 65}
And I need a list of dictionaries back with country and their averages.
I have gotten to a point where I have a list of dictionaries with the sum of price and points:
[{'country': 'Albania', 'points': 176, 'price': 40.0}, {'country': 'Argentina', 'points': 480488, 'price': 116181.0}, {'country': 'Australia', 'points': 430092, 'price': 152979.0}
Now I need to get averages. I was thinking to create another key for country.length and then in the for loop perform a basic calculation. But not sure if this is the right approach... Thanks for help!
My code below:
count_dict = country_count.to_dict()
# Output
{'US': 62139,
'Italy': 18784,
'France': 14785,
'Spain': 8160}
# Get the sum of points and price for each country
grouped_data = wine_data.groupby('country').agg({'points':'sum', 'price':'sum'})
# Reset the index in order to convert df into a list of dictionaries
country_data = grouped_data.reset_index()
country_list = country_data.to_dict('records')
# Output
[{'country': 'Albania', 'points': 176, 'price': 40.0}, {'country': 'Argentina', 'points': 48048 etc]```