How do I insert a column at a specific position in pandas?
Short answer
Use df.insert with the position, name and values, which puts the column exactly where you want rather than at the end. Reordering with a column list is the alternative for bigger rearrangements.
The short version
df.insert(position, name, values) puts a new column at a chosen position rather than appending it at the end. For rearranging several columns at once, selecting them in the order you want is simpler.
Inserting
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2], "c": [3]})
df.insert(1, "new", 0)
print(df.columns.tolist()) # ['a', 'new', 'b', 'c']
The position is zero-based, so 1 means "second column". Unlike most pandas methods, insert modifies the frame in place and returns None, so do not assign its result.
The usual way columns are added
df["new"] = 0 # always goes on the end
That is fine most of the time. Position only matters for a table a person will read, where you want an identifier or a key column at the left rather than buried after twenty other columns.
Reordering instead
For anything more than one insertion, listing the columns in the order you want is clearer.
df = df[["new", "a", "b", "c"]]
This states the whole layout at once, and it fails loudly if you misspell a column, which is a useful safety net.
Moving one column to the front
A common need, which the list approach handles cleanly.
cols = ["id"] + [c for c in df.columns if c != "id"]
df = df[cols]
This puts id first and leaves everything else in its existing order, without hard-coding the full column list, so it keeps working when the data gains new columns.
The duplicate-name error
insert raises if the column name already exists, which is a deliberate guard against silently overwriting a column.
df.insert(1, "a", 0) # ValueError: cannot insert a, already exists
Pass allow_duplicates=True if you genuinely want two columns with the same name, though a frame with duplicate column names is a source of confusion and is best avoided.
Column order does not affect analysis
Worth saying plainly: pandas selects columns by name, so their order has no effect on any calculation, join or aggregation. Reordering is purely presentational. Do it at the end, for the table a human will read, and do not spend effort on it during the analysis itself.