14

I would like to add a column to a dataframe between two columns in number labeled columns dataframe. In the following dataframe the first column corresponds to the index while the first row to the name of the columns.

df
   0 0 1 2 3 4 5
   1 6 7 4 5 2 1
   2 0 3 1 3 3 4
   3 9 8 4 3 6 2 

I have tmp=[2,3,5] that I want to put between the columns 4 and 5, so

df
   0 0 1 2 3 4 5 6 
   1 6 7 4 5 2 2 1
   2 0 3 1 3 3 3 4
   3 9 8 4 3 6 5 2 
emax
  • 6,965
  • 19
  • 74
  • 141
  • 1
    You just need to [add a new column](http://stackoverflow.com/questions/12555323/adding-new-column-to-existing-dataframe-in-python-pandas) and then [order your columns](http://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns)... – Akshat Mahajan Apr 05 '16 at 22:11

2 Answers2

21

You can use insert:

df.insert(4, 'new_col_name', tmp)

Note: The insert method mutates the original DataFrame and does not return a copy.

If you use df = df.insert(4, 'new_col_name', tmp), df will be None.

ayhan
  • 70,170
  • 20
  • 182
  • 203
  • 1
    @RK1 Is there a way to insert a column before a specific column name instead of using the column index? – cms72 Jan 12 '20 at 14:42
  • 9
    @cms72 `insert` doesn't directly support that use case but you can get the column index from column name and pass that: `df.insert(df.columns.get_loc('col_name'), 'new_col_name', ser_to_insert)` – ayhan Jan 12 '20 at 15:35
  • Ah, I see. Thank you! – cms72 Jan 12 '20 at 16:00
  • 2
    "Note: The insert method mutates the original DataFrame and does not return a copy." - this heads up is really important, thank you! – sparc_spread Jan 25 '22 at 18:23
3

First concatenate your column to your dataframe.

df2 = pd.concat([df, pd.DataFrame(tmp)], axis=1)

Then rename the columns to the desired end result.

df2.columns = [0, 1, 2, 3, 4, 6, 5]

Now sort on the renamed columns.

df2.sort_index(axis=1, inplace=True)

>>> df2
   0  1  2  3  4  5  6
0  6  7  4  5  2  2  1
1  0  3  1  3  3  3  4
2  9  8  4  3  6  5  2
Alexander
  • 105,104
  • 32
  • 201
  • 196