Rearranging the rows/index in a pivot table

Question:

Having a dataframe as below:

df = pd.DataFrame({'A': ['John', 'Boby', 'Mina', 'Peter', 'Nicky','Teena'],
      'B': ['John', 'Boby', 'Mina', 'Peter', 'Nicky','Teena'],
      'C': [27, 23, 21, 23, 24,20]})
   
df

I created a pivot table using following code.

a=df.pivot_table(index="A", columns="B", values="C")
a

I need Nicky in the first row of pivot table. Is that possible?

Asked By: Jack

||

Answers:

You can use iloc:

order = [3, 0, 1, 2, 4, 5]
a.iloc[order, order]

Output:

B      Nicky  Boby  John  Mina  Peter  Teena
A                                           
Nicky   24.0   NaN   NaN   NaN    NaN    NaN
Boby     NaN  23.0   NaN   NaN    NaN    NaN
John     NaN   NaN  27.0   NaN    NaN    NaN
Mina     NaN   NaN   NaN  21.0    NaN    NaN
Peter    NaN   NaN   NaN   NaN   23.0    NaN
Teena    NaN   NaN   NaN   NaN    NaN   20.0
Answered By: René

Use reindex on your columns just with the wanted columns first:

first = ['Nicky']
order = first+list(a.index.difference(first))

a.reindex(order)

Output:

B      Boby  John  Mina  Nicky  Peter  Teena
A                                           
Nicky   NaN   NaN   NaN   24.0    NaN    NaN
Boby   23.0   NaN   NaN    NaN    NaN    NaN
John    NaN  27.0   NaN    NaN    NaN    NaN
Mina    NaN   NaN  21.0    NaN    NaN    NaN
Peter   NaN   NaN   NaN    NaN   23.0    NaN
Teena   NaN   NaN   NaN    NaN    NaN   20.0

If you want both Index and columns:

first = ['Nicky']
order = first+list(a.index.union(a.columns).difference(first))
a.reindex(index=order, columns=order)

Output:

B      Nicky  Boby  John  Mina  Peter  Teena
A                                           
Nicky   24.0   NaN   NaN   NaN    NaN    NaN
Boby     NaN  23.0   NaN   NaN    NaN    NaN
John     NaN   NaN  27.0   NaN    NaN    NaN
Mina     NaN   NaN   NaN  21.0    NaN    NaN
Peter    NaN   NaN   NaN   NaN   23.0    NaN
Teena    NaN   NaN   NaN   NaN    NaN   20.0

reindex vs loc

If you use this code on arbitrary input, Nick might be missing. In such case loc will raise an error as the key is not found. reindex will just create the missing indices.

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.