Syntax error How to change the order of Pandas DataFrame columns?

How to change the order of Pandas DataFrame columns?



To change the order of DataFrame columns, we can take the following Steps −

Steps

  • Make two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print the input DataFrame.

  • Get the list of DataFrame columns, using df.columns.tolist()

  • Change the order of DataFrame columns.

  • Modify the order of columns of the DataFrame.

  • Print the DataFrame after changing the columns order.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)
print "Input DataFrame is:
", df cols = df.columns.tolist() cols = cols[-1:] + cols[:-1] df = df[cols] print "After changing the order:
", df

Output

Input DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

After changing the order:
   z  x  y
0  4  5  4
1  1  2  1
2  5  1  5
3  0  9 10
Updated on: 2021-08-30T09:30:30+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements