Maho Takahashi

Linguistics PhD

research

CV

code

mtakahas[at]ucsd[dot]edu

How to reorder rows and columns in a pandas dataframe

import pandas as pd
df = pd.DataFrame({'Discount':[10, 8, 20, 15, 10],
                   'Product':[' UMbreLla', '  maTress', 'BeDmintoN ', 'Shuttle', 'jaCket  '],
                   'Updated_Price':[880, 1250, 1450, 1550, 400],
                   'Date':['10/2/2011', '10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011']})
df
Discount Product Updated_Price Date
0 10 UMbreLla 880 10/2/2011
1 8 maTress 1250 10/2/2011
2 20 BeDmintoN 1450 11/2/2011
3 15 Shuttle 1550 12/2/2011
4 10 jaCket 400 13/2/2011

reorder columns

new_index = ['Date','Updated_Price','Product_new','Discount']
df = df.reindex(new_index, axis="columns")
df
Date Updated_Price Product_new Discount
0 10/2/2011 880 NaN 10
1 10/2/2011 1250 NaN 8
2 11/2/2011 1450 NaN 20
3 12/2/2011 1550 NaN 15
4 13/2/2011 400 NaN 10

reverse columns

df[df.columns[::-1]]
Discount Product_new Updated_Price Date
3 15 NaN 1550 12/2/2011
2 20 NaN 1450 11/2/2011
1 8 NaN 1250 10/2/2011
0 10 NaN 880 10/2/2011
4 10 NaN 400 13/2/2011

reorder rows

df.sort_values(by ='Updated_Price', ascending = 0, inplace=True)
df
Date Updated_Price Product_new Discount
3 12/2/2011 1550 NaN 15
2 11/2/2011 1450 NaN 20
1 10/2/2011 1250 NaN 8
0 10/2/2011 880 NaN 10
4 13/2/2011 400 NaN 10

reverse rows

df.loc[::-1]
Date Updated_Price Product_new Discount
4 13/2/2011 400 NaN 10
0 10/2/2011 880 NaN 10
1 10/2/2011 1250 NaN 8
2 11/2/2011 1450 NaN 20
3 12/2/2011 1550 NaN 15

shuffle rows

df.sample(frac=1)
Discount Product Updated_Price Date
0 10 UMbreLla 880 10/2/2011
2 20 BeDmintoN 1450 11/2/2011
3 15 Shuttle 1550 12/2/2011
1 8 maTress 1250 10/2/2011
4 10 jaCket 400 13/2/2011