user8738575
user8738575

Reputation:

Python Pandas - check value in two columns, sum the 3rd column

I have a dataset which looks similar to this (but 10000 rows instead of 6, and 100 different artists and more genres:

Year Genre Artist Cost
2018 Classical Bach 5
2019 Jazz Beethoven 6
2019 Rock Mozart 10
2020 Classical Beethoven 5
2019 Rock Beethoven 10
2020 Classical Beethoven 3

Using Pandas I want to create a break down of the total cost, for example for Beethoven:

Genre Total Cost
Classical 8
Jazz 6
Rock 10

I know I can have conditional summation using .loc as shown below which works in adding the total cost of classical songs

df.loc[df['Genre'] == 'Classical',Cost].sum()

So basically, Pandas docs only show examples with a single conditional like I have above and I want to be able to check both the Genre and Artist columns and sum by Genre for each Artist

Upvotes: 0

Views: 269

Answers (1)

Joshua Voskamp
Joshua Voskamp

Reputation: 2054

What's your expected output? Does

df.groupby(['Genre','Artist']).Cost.sum()

do what you want?

Upvotes: 1

Related Questions