Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Empty pivot table with pandas data frames

I have checked around, but it seems I can’t find this question (or at least an answer) anywhere.
Say I have this data frame with empty cells

data = pd.DataFrame( {'A': {0: 'a1', 1: 'a1', 2: 'a1', 3: 'a1', 4: 'a1', 5: 'a2', 6: 'a2', 7: 'a2', 8: 'a2', 9: 'a2'}, 'B': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: 'bb', 6: 'bc', 7: 'bd', 8: 'be', 9: 'bf'}, 'col': {0: 10, 1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 7: 10, 8: 10, 9: 10}, 'C': {0: 'c1', 1: 'c1', 2: 'c1', 3: 'c1', 4: 'c1', 5: 'c2', 6: 'c2', 7: 'c2', 8: 'c2', 9: 'c2'}, 'D': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}, 'E': {0: 'e1', 1: 'e2', 2: 'e3', 3: 'e4', 4: 'e5', 5: nan, 6: nan, 7: nan, 8: nan, 9: nan}} )

enter image description here

I’d like to pivot column values, so I’m trying:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pivot = pd.pivot_table(data, values='D', index=['A', 'B', 'C', 'E'], columns=['col'])

I’d expect something like

enter image description here

Instead, I get an empty table. Can anyone help here?

>Solution :

pivot = pd.pivot(data, values='D', index=['A', 'B', 'C', 'E'], columns=['col'])

If you want to reset the index you can use pivot.reset_index() which returns:

col   A    B   C    E  10
0    a1  NaN  c1   e1   0
1    a1  NaN  c1   e2   0
2    a1  NaN  c1   e3   0
3    a1  NaN  c1   e4   0
4    a1  NaN  c1   e5   0
5    a2   bb  c2  NaN   0
6    a2   bc  c2  NaN   0
7    a2   bd  c2  NaN   0
8    a2   be  c2  NaN   0
9    a2   bf  c2  NaN   0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading