move a pandas dataframe column to position in python

To move a column in a Pandas DataFrame to a specific position, you can use the DataFrame.insert() method. The method takes three arguments: the index of the column you want to move, the column name, and the value of the column.

Here's an example to move a column called col_name to the second position in the DataFrame df:

main.py
col_name = 'column_name'
second_position = 1

column = df.pop(col_name)
df.insert(second_position, col_name, column)
117 chars
6 lines

In this example, we first pop the column from the DataFrame using the DataFrame.pop() method, which removes and returns the specified column. We then insert the column to the desired position using the DataFrame.insert() method.

Note that the column index positions start from 0. So the second position is actually index 1.

related categories

gistlibby LogSnag