how to change placement of columns of existing columns in a dataframe in python

To change the placement of columns in a dataframe you can simply re-order them using indexing.

Here is an example:

Suppose you have a dataframe df which looks like below:

main.py
    Name    Age    Gender    Salary
0   John    25     M         50000
1   Alice   30     F         60000
2   Bob     35     M         70000
141 chars
5 lines

You want to move the Salary column to the first position.

Here's how you can do it:

main.py
df = df[['Salary', 'Name', 'Age', 'Gender']]
45 chars
2 lines

This will re-order the columns in df and the resulting dataframe will look like this:

main.py
    Salary  Name    Age    Gender
0   50000   John    25     M
1   60000   Alice   30     F
2   70000   Bob     35     M
121 chars
5 lines

related categories

gistlibby LogSnag