Reorder columns in a pandas DataFrame
Select columns in a new order, move a single column with pop and insert, and understand how selection differs from reindex.
Select columns using a list in the order you want: df = df[['c', 'a', 'b']]. Include every column you want to retain; omitted columns are left out of the result.
Set the complete order
import pandas as pd
df = pd.DataFrame({
'city': ['London'], 'age': [30], 'name': ['Ada'], 'id': [1],
})
df = df[['id', 'name', 'age', 'city']]
# Put selected columns first; preserve the rest in their current order
first = ['id', 'name']
columns = first + [column for column in df.columns if column not in first]
df = df[columns]
These examples assume unique column labels. If labels are duplicated, selection can produce more columns than the list alone suggests; resolve that ambiguity before reordering.
Move one column
df['score'] = [95]
score = df.pop('score')
df.insert(0, 'score', score) # Move score to the front
score = df.pop('score')
df.insert(2, 'score', score) # Move it to the third position
pop() removes the column and returns it. insert() mutates the DataFrame at the specified position. Validate the destination before changing a valuable frame: if insertion fails after a pop, the column has already been removed.
Sort column labels
df = df[sorted(df.columns)]
# Alternative for sortable column labels:
df = df.sort_index(axis=1)
Alphabetical ordering is convenient for all-string labels. Mixed label types may not have a meaningful shared ordering; use an explicit list when order matters to an output schema.
FAQ
How is reindex different from selection?
df[['missing']] raises KeyError. df.reindex(columns=['missing']) can create the absent column filled with missing values. Both can omit existing columns, so check the desired schema before replacing your variable.
Can I reorder in place?
The pop/insert approach mutates the existing DataFrame. df = df[columns] rebinds the variable to the returned DataFrame; other references do not automatically point to it. Do not rely on the result being a writable view of the original, especially across pandas versions and copy-on-write behavior.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan