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?
DataFrame.sort_index(axis=1)
is quite clean.Check doc here. And thenconcat
From August 2018:
If your column names are too long to type then you could specify the new order through a list of integers with the positions:
And for the specific case of OP's question:
Just type the column name you want to change, and set the index for the new location.
For your case, this would be like:
@clocker: Your solution was very helpful for me, as I wanted to bring two columns in front from a dataframe where I do not know exactly the names of all columns, because they are generated from a pivot statement before. So, if you are in the same situation: To bring columns in front that you know the name of and then let them follow by "all the other columns", I came up with the following general solution;
I tried the
insert()
function as suggested by Wes McKinney.This got the result that Timmie wanted, in one line, without the need to move that last column.
Just assign the column names in the order you want them:
Now, 'mean' column comes out in the front: