Search⌘ K
AI Features

Challenge 2: Sum of Plays per Country + Genre (Trivial)

Explore how to sum the number of plays for each country and genre combination using Pandas grouping methods. This lesson helps you understand grouping DataFrames by multiple columns and applying aggregation functions to analyze categorical data effectively.

Problem definition

Your music analyst has realized that it’s unfair to view the total number of plays per country without counting in the effect of genres. Can you return the total number of plays per each country/genre combination?

Expected output

A Python dictionary, where every key is a tuple of (country_name, genre), and the value is the number of plays of this particular country-genre combination

Example: {("Egypt", "rock"): 1000}

Challenge

Python 3.5
import pandas as pd
def test():
df = pd.read_csv('music.csv')
pass

Solution

Python
import pandas as pd
def test():
df = pd.read_csv('music.csv')
return df.groupby(['country', 'genre']).plays.sum().to_dict()
print(test())

Solution explanation

The solution given above is almost identical to that of Challenge 1 (Sum of Plays per Country). The only difference is that in the .groupby() function call, you supply a list of the columns you would like your data to be grouped with, which, in this case, are country and genre.

Any applied functions over this DataFrameGroupBy returned object will be on the combinations of country and genre.