Modifying Data
Once you can select data, the natural next step is changing it — adding computed columns, dropping ones you don't need, and handling missing values, which show up in almost every real dataset.
Adding a column
Assigning to a column name that doesn't exist yet creates it. New columns are often computed from existing ones:
import pandas as pd
df = pd.DataFrame({
"product": ["Notebook", "Pen"],
"quantity": [4, 10],
"price": [3.50, 1.20]
})
df["total"] = df["quantity"] * df["price"]
print(df)
product quantity price total 0 Notebook 4 3.50 14.0 1 Pen 10 1.20 12.0
df["quantity"] * df["price"] multiplies two columns element-by-element, row for row — no loop required.
Dropping columns and rows
df2 = df.drop(columns=["price"]) print(df2)
product quantity total 0 Notebook 4 14.0 1 Pen 10 12.0
.drop() returns a new DataFrame by default rather than changing df in place — that's why this example assigns the result to df2. Pass inplace=True if you genuinely want to modify the original.
Missing data
Real data almost always has gaps. pandas represents a missing value as NaN, and gives you three main tools for it:
import numpy as np
df = pd.DataFrame({"name": ["Maya", "Sam", "Priya"], "score": [88, np.nan, 79]})
print(df.isna())
print(df.fillna(0))
print(df.dropna())
name score
0 False False
1 False True
2 False False
name score
0 Maya 88.0
1 Sam 0.0
2 Priya 79.0
name score
0 Maya 88.0
2 Priya 79.0.isna() shows where the gaps are, .fillna(0) replaces them with a value you choose, and .dropna() removes any row containing a NaN entirely. Which one is right depends entirely on what a missing value means for your data — filling with 0 is only correct when 0 is a genuinely reasonable stand-in.
subset = df[df["score"] > 80]; subset["score"] = 0 — triggers a SettingWithCopyWarning, because pandas can't always tell whether subset is an independent copy or a view into the original df. Use df.loc[df["score"] > 80, "score"] = 0 instead to modify the original safely and directly.