← Back to Pandas Course | Chapter 3: DataFrame Basics | Lesson 5 of 7

Adding/dropping columns

Create new columns by assigning to a new name and remove old ones with drop.

In this page:

  1. Adding/dropping columns
Syntax
python
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

python
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
  1. Forgetting drop returns a new DataFrame
  2. Using axis incorrectly
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.