I have the following DataFrame
(df
):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
I add more column(s) by assignment:
df['mean'] = df.mean(1)
How can I move the column mean
to the front, i.e. set it as first column leaving the order of the other columns untouched?
You could do the following (borrowing parts from Aman's answer):
Here's a way to move one existing column that will modify the existing data frame in place.
One easy way would be to reassign the dataframe with a list of the columns, rearranged as needed.
This is what you have now:
Rearrange
cols
in any way you want. This is how I moved the last element to the first position:Then reorder the dataframe like this:
Moving any column to any position:
You could also do something like this:
You can get the list of columns with:
The output will produce:
...which is then easy to rearrange manually before dropping it into the first function
You need to create a new list of your columns in the desired order, then use
df = df[cols]
to rearrange the columns in this new order.You can also use a more general approach. In this example, the last column (indicated by -1) is inserted as the first column.
You can also use this approach for reordering columns in a desired order if they are present in the DataFrame.