0

I created a 'new' column in the dataframe. Now I want to add this 'new' column between columns B and C. Please suggest how to do it.

df = pd.DataFrame({'A':[10,0,200,50,500],'B': [50,200,70,90,800],'C':[100,500,60,300,70]})
df['new'] = ((df['C'] - df['B'])/df['B']) * 100
Rahul
  • 129
  • 1
  • 10
  • Does this answer your question? [How to change the order of DataFrame columns?](https://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns) – Henry Yik Feb 03 '20 at 03:06

2 Answers2

3

you can use pandas.DataFrame.iloc to arrange your columns

>>> df = df.iloc[:, [0,1,3,2]]    # After new column
>>> df
     A    B         new    C
0   10   50  100.000000  100
1    0  200  150.000000  500
2  200   70  -14.285714   60
3   50   90  233.333333  300
4  500  800  -91.250000   70
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
3

This is DataFrame.insert. Though really the condition would be after column B.

#df = pd.DataFrame({'A': [10, 0, 200, 50, 500],
#                   'B': [50, 200, 70, 90, 800],
#                   'C': [100, 500, 60, 300, 70]})

df.insert(loc=df.columns.get_loc('B')+1,       # After column 'B'
          column='new',                        # named `'new'`
          value=(df['C'] - df['B'])/df['B']*100)

print(df)

     A    B         new    C
0   10   50  100.000000  100
1    0  200  150.000000  500
2  200   70  -14.285714   60
3   50   90  233.333333  300
4  500  800  -91.250000   70
ALollz
  • 57,915
  • 7
  • 66
  • 89