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?
How about using "T"?
set()
:A simple approach is using
set()
, in particular when you have a long list of columns and do not want to handle them manually:How about:
http://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion
I believe @Aman's answer is the best if you know the location of the other column.
If you don't know the location of
mean
, but only have its name, you cannot resort directly tocols = cols[-1:] + cols[:-1]
. Following is the next-best thing I could come up with:I liked Shoresh's answer to use set functionality to remove columns when you don't know the location, however this didn't work for my purpose as I need to keep the original column order (which has arbitrary column labels).
I got this to work though by using IndexedSet from the boltons package.
I also needed to re-add multiple column labels, so for a more general case I used the following code:
Hope this is useful to anyone searching this thread for a general solution.
This question has been answered before but reindex_axis is deprecated now so I would suggest to use: