Pandas Adding & Changing Columns

Create new columns from existing ones.

✍️ 3 exercises + code challenge in this lesson
  • New column from a calculation: df["total"] = df["price"] * df["qty"]
  • Apply a function to each value: df["grade"] = df["marks"].apply(fn)
  • Rename: df.rename(columns={"old": "new"})
  • Remove: df.drop(columns=["col"])

Key Takeaways: Pandas Adding & Changing Columns

Mastering Pandas Adding & Changing Columns helps you write clean and reliable Pandas code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Pandas Adding & Changing Columns Code Example

Pandas
import pandas as pd

df = pd.DataFrame({"item": ["Pen", "Book", "Bag"], "price": [50, 400, 2500], "qty": [10, 3, 1]})
df["total"] = df["price"] * df["qty"]
df["size"] = df["total"].apply(lambda t: "big" if t >= 1000 else "small")
print(df)
Output
item  price  qty  total   size
0   Pen     50   10    500  small
1  Book    400    3   1200    big
2   Bag   2500    1   2500    big
Free sign-in required · Google login available

Pandas Adding & Changing Columns Practice Exercises

Check what you learned in “Pandas Adding & Changing Columns”.

/ 3 solved
Fill in the blank

Add a new column called total.

df[""] = df["price"] * df["qty"]
✓ Correct! Not quite. Try again.
Multiple choice

Which method runs a function on every value of a column?

✓ Correct! Not quite. Try again.
Code challenge

Add a column bonus = salary * 0.1 and print the bonus of Ali.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services