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:

>>> a computed column
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)
Output
    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

>>> dropping
df2 = df.drop(columns=["price"])
print(df2)
Output
    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:

>>> handling NaN
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())
Output
    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.

The single most common pandas warning: filtering into a subset and then assigning to it — 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.