0

I have a dataset with various types of student data. I'm trying to create a pivot table that shows how many of each sex prefer a specific genre of music but right now it's just aggregating all of the M/F strings. This is the code I currently have:

pivot= df.pivot_table(index= 'Favorite_Music_Genre', values= 'Gender', aggfunc= 'sum')

And this is the output:

enter image description here

I assume it has something to do with 'aggfunc'. Please help!

4
  • so you want the count of M and F, have you tried to replace sum by count Commented Mar 15, 2021 at 22:25
  • yes, that is what i meant sorry Commented Mar 15, 2021 at 22:27
  • you're welcome, happy to help! Commented Mar 15, 2021 at 22:29
  • please post a small sample of your df (as text so it can be copy-pasted) Commented Mar 15, 2021 at 22:54

2 Answers 2

2

You try to sum strings, which will then concatenate them. Try using aggfunc='count', it should work :)

Edit: You can add a temporary column set to 1 for it to be the structure you want:

pivot = df.assign(val=1).pivot_table(values='val', index='Favorite_Music_Genre', columns='Gender', aggfunc='count')
Sign up to request clarification or add additional context in comments.

3 Comments

Actually I suppose I should clarify, I am trying to display the number of each sex that prefers a specific music genre, so rather than a total count it's broken down into M and F
Yop, that is what a pivot table does, but doesn't it work with count instead of sum?
count displays the total number of ppl for each genre, but it isnt broken down into sex
1

This could work:

df = df.reset_index(drop=True)
for i in range(len(df)):
    genre = df['Favorite_Music_Genre'][i]
    text  = df['Gender'][i]
    print('Number of F in',genre,'is',df['Gender'][i].count('F'))
    print('Number of M in',genre,'is',df['Gender'][i].count('M'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.