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

pivot and preserve column/row order in pandas

df = pd.DataFrame({'foo': ['two', 'two', 'two', 'one', 'one','one'],
                   'bar': ['B', 'A', 'C', 'B', 'A', 'C'],
                   'baz': [1, 2, 3, 4, 5, 6],
                   'zoo': ['x', 'y', 'z', 'q', 'w', 't']})

df.pivot(index='foo', columns='bar', values='baz')

bar  A  B  C
foo         
one  5  4  6
two  2  1  3

How can I prevent pivot from sorting rows and columns?
Desired output:

bar  B  A  C
foo         
two  1  2  3
one  4  5  6

>Solution :

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

First idea is use ordered Categorical, so pivoting return correct ordering:

df['foo'] = pd.Categorical(df['foo'], ordered=True, categories=df['foo'].unique())
df['bar'] = pd.Categorical(df['bar'], ordered=True, categories=df['bar'].unique())
df1 = df.pivot(index='foo', columns='bar', values='baz')
print (df1)
bar  B  A  C
foo         
two  1  2  3
one  4  5  6

Or is possible change order by DataFrame.reindex:

df1 = (df.pivot(index='foo', columns='bar', values='baz')
         .reindex(index=df['foo'].unique(), columns=df['bar'].unique()))
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