ineedshelp
ineedshelp

Reputation: 33

Dataframe pivot without sorting the column names?

Original data :-

date   variable    value
2017    A             1
2017    C             1
2017    B             2
2018    A             1
2018    C             1
2018    B             2

My pivot Result :-

date   A        B        C
2017   1        2        1
2018   1        2        1

Expected Output :-

date   A     C     B
2017   1     1     2
2018   1     1     2

Upvotes: 2

Views: 2129

Answers (2)

Edel
Edel

Reputation: 92

The following command (from how can i unstack without sorting in pandas?) is ok for me :

print(df.unstack(0).reindex(pd.unique(df.index.get_level_values(1))).sort_index(axis=1,level=1).T)

and returns :

      A  C  B
2017  1  1  2
2018  1  1  2

Upvotes: 0

anky
anky

Reputation: 75080

You can achieve this with pd.Categorical:

df.variable=pd.Categorical(df.variable,categories=df.variable.unique(),ordered=True)
df.pivot_table(index='date',columns='variable',values='value')

variable  A  C  B
date             
2017      1  1  2
2018      1  1  2

This sets the order as df.variable.unique() which is [A, C, B]

Upvotes: 6

Related Questions