Sub topic 2
Conditional and cleaned columns in pandas
Assume you know how to create a DataFrame, select columns, and write basic Python functions. The examples use pandas and NumPy.
Conditional columns with `np.where` and `np.select`
np.where(condition, value_if_true, value_if_false) chooses between two values for each row. np.select handles several conditions in order.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": ["1.50", "12.00", "30.00"],
"name": [" Ann Lee", "bob ray ", "Cara Fox"],
"joined": ["2026-01-15", "2026-02-03", "2026-03-20"],
"code": ["P", "B", "X"],
})
df["expensive"] = np.where(
pd.to_numeric(df["price"]) >= 20,
"yes",
"no",
)
df["tier"] = np.select(
[
pd.to_numeric(df["price"]) < 5,
pd.to_numeric(df["price"]) < 20,
],
["low", "mid"],
default="high",
)np.select tests conditions from top to bottom. The first true condition wins.
Converting column types
Use astype when values are already valid and have a known type. Use to_numeric when bad input should become missing data. Use to_datetime for dates.
df["price"] = pd.to_numeric(df["price"], errors="coerce")
df["joined"] = pd.to_datetime(df["joined"], errors="coerce")
df["item"] = df["item"].astype("string")errors="coerce" converts invalid values to NaN or NaT, which you can inspect and handle later.
Cleaning text with `.str`
The .str accessor applies string operations element by element.
df["name_clean"] = df["name"].str.strip().str.title()
df["first_name"] = df["name_clean"].str.split().str[0]Extracting date parts with `.dt`
After conversion to datetime, .dt extracts components such as the month or year.
df["join_year"] = df["joined"].dt.year
df["join_month"] = df["joined"].dt.monthRecoding with `map` and `replace`
map looks up each value in a dictionary. Unmatched values become missing. replace is useful when you want unmatched values to remain unchanged.
df["item_label"] = df["code"].map({
"P": "Product",
"B": "Book",
}).fillna("Unknown")
df["item"] = df["item"].replace({
"pen": "writing tool",
"book": "reading material",
})Exercise
Which method should you use to convert invalid numeric strings to missing values?
Show answer
Use pd.to_numeric(column, errors="coerce").