2

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
ineedshelp
  • 23
  • 5

2 Answers2

5

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]

anky
  • 74,114
  • 11
  • 41
  • 70
0

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
Edel
  • 92
  • 5