Python Pandas Pivot - Why Doesn't Work

I tried for a while to get this, and I can’t - I read the documentation and I have to misunderstand something

I have a Data Frame in a long format, and I want to make it wide - this is pretty 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 (part of lats, since they are quite extensive): ValueError: cannot mark an index with a null key

I tried this in python (notebook) as well as on a regular python c command line in OS X with the same result

Thank you for your understanding, I'm sure it will be something basic

+5
source share
1 answer

From what you were trying to do, you were trying to pass the “group” as index so that the failure would occur. 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 quite sure what expected result you want, if you just want a short presentation, you can always use transpose :

 data.T 

or, best for presentation in your case, groupby :

 data.groupby('group').sum() value group a 6 b 22 c 27 d 23 
+8
source

Source: https://habr.com/ru/post/1206278/


All Articles