Skip to content
Advertisement

Groupby aggregate and transpose in pandas

df=

JavaScript

Off all the genres in the genre field, I only need to consider ‘Rock’, ‘Latin’, ‘Metal’, ‘Blues’ and build a new dataframe based on the following requirements

a.how many songs the singer has from that genre (count of each genre must be in a separate column).

b.Count of how many albums the singer has in the data.

c.Count of how many tracks the singer has in the data.

d.Count of how many playlists that include any Song of the singer.

Desired Output:

JavaScript

I was going to create one df for part a and one for parts b,c,d and merge them.

For parts b,c and d. I thought of looping over singer names and using nunique to get distinct count, but did not realize, the loop would also return column headers everytime.

JavaScript

For part A, I was going to group songs by genre find a count and do a transpose

JavaScript

Any help will be greatly appreciated!

Advertisement

Answer

Can be done in one line but it’s a bit of a mouthful…

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement