how do I insert a column at a specific column index in pandas?

HappyPy picture HappyPy · Sep 7, 2013 · Viewed 265.3k times · Source

Can I insert a column at a specific column index in pandas?

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

This will put column n as the last column of df, but isn't there a way to tell df to put n at the beginning?

Answer

Jeff picture Jeff · Sep 7, 2013

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6