olivier dadoun
olivier dadoun

Reputation: 743

order while using pivot_table

How can I keep the initial order of my pandas while I using pivot_table ?

I use pandas version '1.2.5' (so I can't use the pivot_table "order" argument)

For instance

data =pd.DataFrame(data={
'x_values':[13.4, 13.08, 12.73],
'y_values': [1.54, 1.47, 1.46],
'experiment':['e', 'e', 'e']})

gives

   x_values  y_values experiment
0     13.40      1.54          e
1     13.08      1.47          e
2     12.73      1.46          e

and if I use pivot_table the order of my initial pandas is not kept

data =  pd.pivot_table(data, index='x_values', columns='experiment', values='y_values')

gives

experiment     e
x_values        
12.73       1.46
13.08       1.47
13.40       1.54

In the real code I don't know the order of x_values.

I just want to keep the order as it is in my pandas ...

Upvotes: 0

Views: 68

Answers (2)

olivier dadoun
olivier dadoun

Reputation: 743

The simplest way is to upgrade the pandas version (min 1.3.0) and use 'sort' argument

data =  pd.pivot_table(data, index='x_values', columns='experiment', values='y_values')

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

Due to nature of pivot it always sort the index. You might want to pivot with the original index.

data.reset_index().pivot_table(index=['index','x_values'], values='y_values', columns='experiment')

You can also use set_index().unstack():

data.set_index(['x_values', 'experiment'], append=True)['y_values'].unstack('experiment')

Output:

experiment     e
  x_values      
0 13.40     1.54
1 13.08     1.47
2 12.73     1.46

Upvotes: 1

Related Questions