Two Solutions for pandas to Reverse Column Order

  • 2021-10-16 02:07:22
  • OfStack

In the process of data preprocessing, it may be necessary to reverse the order of columns. There are two methods.


import numpy as np
import pandas as pd
df = pd.DataFrame(np.array(range(20)).reshape(4,5))
print(df)

The original dataframe is as follows:


  0  1  2  3  4
0  0  1  2  3  4
1  5  6  7  8  9
2 10 11 12 13 14
3 15 16 17 18 19

1. Method 1

Manually set the column name list, which is applied in dataframe (suitable for the situation with few column names)

We can change the order of columns manually


cols = [4,3,2,1,0]
df = df.ix[:,cols]
print(df)

The output is as follows:


  4  3  2  1  0
0  4  3  2  1  0
1  9  8  7  6  5
2 14 13 12 11 10
3 19 18 17 16 15

2. Method 2

pandas provides a way to reverse the order of columns

It can be seen that when there are many columns of data, Method 1 will be very cumbersome, and pandas provides a very simple way to reverse the column order.


df = df.ix[:, ::-1]
print(df)

The output is as follows:


  4  3  2  1  0
0  4  3  2  1  0
1  9  8  7  6  5
2 14 13 12 11 10
3 19 18 17 16 15

Supplement: Python list sorting and reverse ordering

python Study Notes

List sorting

1. sort ()

2. sorted ()

3. reverse ()

Use of sort ()


letters = ['d','a','e','c','b']
print letters
['d','a','e','c','b']
letters.sort()
print letters
['a','b','c','d','e']

sort () automatically sorts strings from small to large in alphabetical order, and if numbers are small to large

Note: sort () modifies the original list instead of creating a new one.

Shouldn't


print letters.sort()

And should


letters.sort()
print letters

You can also use the. sorted () function


#  Get 1 Ordered list of copies 
# Without affecting the order of the original list 
old = ['d','a','e','c','b']
new = sorted(old)
print old
['d','a','e','c','b']
print new
['a','b','c','d','e']

Use of reverse


  0  1  2  3  4
0  0  1  2  3  4
1  5  6  7  8  9
2 10 11 12 13 14
3 15 16 17 18 19
0

Related articles: