Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Pivot - Why Fails

I have tried for a while to get this to wrk and I can't - I read the documentation and I must be misunderstanding something

I have a Data Frame in long format and I want to make it wide - this is quite common. But I get an error

from pandas import DataFrame 
data = DataFrame({'value' : [1,2,3,4,5,6,7,8,9,10,11,12],
                  'group' : ['a','a','a','b','b','b','b','c','c','c','d','d']})
data.pivot(columns='group')

the error I get is (the lats part, as they are quite extensive): ValueError: cannot label index with a null key

I tried this in python (notebook) and also on regular python c command line in OS X with the same result

Thanks for any insight, I am sure it will be something basic

like image 241
user1617979 Avatar asked Nov 05 '14 19:11

user1617979


1 Answers

From what you were trying to do, you were trying to pass 'group' as index so the pivot fails. It should be:

data.pivot(data.index, 'group')

or,

# the format is pivot(index=None, columns=None, values=None)
data.pivot(index=data.index, columns='group')

However I'm not entirely sure what expected output you want, if you just want shorter presentation, you can always use transpose:

data.T

or, the best for presentation in your case, is groupby:

data.groupby('group').sum()
       value
group       
a          6
b         22
c         27
d         23
like image 164
Anzel Avatar answered Sep 21 '22 00:09

Anzel