Home > front end >  Python DataFrame pivot_table not returning column headers
Python DataFrame pivot_table not returning column headers

Time:09-17

I have the following df that I am trying to pivot by '

data = {'Country': ['India','India', 'India','India','India', 
'USA','USA'],
'Personality': ['Sachin Tendulkar','Sachin Tendulkar','Sania Mirza','Sachin Tendulkar', 'Sania 
 Mirza', 'Serena Williams','Venus Willians'] }
 #create a dataframe from the data
 df = pd.DataFrame(data, columns = ['Country','Personality'])

My issue is with the following line of code:

df.pivot_table(index=['Country'],
                columns=['Personality'],values='Personality', aggfunc='count', fill_value=0)

I expect the op to look like the following:

       Sachin Tendulkar Sania Mirza Serena Williams Venus Williams
Country
India   3                2             0               0
USA     0                0             1               1

However, all I see is the Index column after running the above code.

CodePudding user response:

If you put len in for aggfunc, it works:

df.pivot_table(index='Country', columns='Personality', values='Personality', aggfunc=len, fill_value=0)

Output:

Personality  Sachin Tendulkar  Sania Mirza  Serena Williams  Venus Willians
Country                                                                    
India                       3            2                0               0
USA                         0            0                1               1
  • Related