how do I insert a column at a specific column index in pandas?
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]})dfOut: B C0 1 41 2 52 3 6idx = 0new_col = [7, 8, 9] # can be a list, a Series, an array or a scalar df.insert(loc=idx, column='A', value=new_col)dfOut: A B C0 7 1 41 8 2 52 9 3 6
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need>>> df.reindex(columns=cols) n l v0 0 a 11 0 b 22 0 c 13 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist()) n l v0 0 a 11 0 b 22 0 c 13 0 d 2