My question is similar to this question. In answers of that question i saw few ways to do what i am trying to do below. But answers are old and i feel that there might be a fast and an efficient way to do what i am looking for.
import pandas as pd
df =pd.DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})
df['x']=df.a + df.b
df['y']=df.a - df.b
df
a b x y
0 1 2 3 -1
1 2 4 6 -2
2 3 6 9 -3
3 4 8 12 -4
Now I want to move x and y columns to beginning. I can always do below.
df = df[['x','y','a','b']]
df
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
But I don't want that solution. I want an efficient solution that would move columns x and y to beginning without mentioning names of other columns as my dataframe is going to change and i might not know names of all the columns