- 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"])
Pandas Adding & Changing Columns
Create new columns from existing ones.
✍️ 3 exercises + code challenge in this lessonKey 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
Pandasimport 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)
item price qty total size 0 Pen 50 10 500 small 1 Book 400 3 1200 big 2 Bag 2500 1 2500 big
Pandas Adding & Changing Columns Practice Exercises
Check what you learned in “Pandas Adding & Changing Columns”.
Add a new column called total.
df[""] = df["price"] * df["qty"]
Which method runs a function on every value of a column?
Add a column bonus = salary * 0.1 and print the bonus of Ali.
Free sign-in required · Google login available
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