HappyPy HappyPy - 6 months ago 21
Python Question

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

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

see docs: http://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion

using idx = 0 will insert at the beginning

df.insert(idx, col_name, value)