0

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

Ni_Tempe
  • 307
  • 1
  • 6
  • 20

2 Answers2

1

You can using insert

df.insert(loc=0, column='x', value=df.a + df.b)
df.insert(loc=1, column='y', value=df.a - df.b)
df
Out[325]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8
BENY
  • 317,841
  • 20
  • 164
  • 234
  • is `value=df.a + df.b` part required? I tried `df.insert(loc=0, column='x',value='x')`, but it failed :(. I did it this way because i am reading a csv and my column `x` has static values – Ni_Tempe Mar 16 '18 at 18:10
  • In your example x is calculated by df.a + df.b right ? @Ni_Tempe – BENY Mar 16 '18 at 18:11
  • @Ni_Tempe so you have it x, y in another dataframe ? – BENY Mar 16 '18 at 18:12
  • no i have a csv file and i am reading that file to create my dataframe – Ni_Tempe Mar 16 '18 at 18:22
  • @Ni_Tempe consider change your question with some sample data , since in your original post we do not get any information about the point you mention in the comment – BENY Mar 16 '18 at 19:14
0
import pandas as pd

df =pd.DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})

a = list(df.columns)

df['x']=df.a + df.b

df['y']=df.a - df.b

b = list(df.columns)

diff = list(set(b) - set(a))

df[diff+a]
df

 y   x  a  b
-1   3  1  2
-2   6  2  4
-3   9  3  6
-4  12  4  8
Lokin
  • 9
  • 3
  • it wont work as the columns that i want to move could be anywhere in the dataframe...they could be in middle or at the end... – Ni_Tempe Mar 16 '18 at 18:23
  • The columns which you want to move either at the middle or end in the data frame should always be at the beginning ? @Ni_Tempe – Lokin Mar 16 '18 at 18:28