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.py117 chars6 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.
gistlibby LogSnag