Adding/dropping columns
Create new columns by assigning to a new name and remove old ones with drop.
In this page:
Syntax
df["new_column"] = df["column1"] * df["column2"]
df = df.drop(columns=["column"])
Adding/dropping columns
Assign df["new"] = ... to add a column computed from others. drop(columns=[...]) removes columns and returns a new DataFrame unless inplace=True. assign() adds columns and returns a new DataFrame, which suits method chaining.
Note:
Prefer df = df.drop(...) over inplace=True; it reads more clearly and chains better.
Example: Adding/dropping columns
import pandas as pd
df = pd.DataFrame({"price": [10, 20], "qty": [3, 5]})
df["total"] = df["price"] * df["qty"]
print(df)
print(df.drop(columns=["qty"]))
print(df.assign(tax=df["total"] * 0.1))
# Output:
# price qty total
# 0 10 3 30
# 1 20 5 100
# price total
# 0 10 30
# 1 20 100
# price qty total tax
# 0 10 3 30 3.0
# 1 20 5 100 10.0
Related Topics
Common Mistakes
- Forgetting drop returns a new DataFrame
- Using axis incorrectly
- Assigning a list of the wrong length
Chapter Summary
- Assign to add a column
- drop(columns=...) removes
- assign supports chaining
- List length must match rows
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: