Sub topic 3
Adding and Transforming Columns
Assume basic Python, pandas Series and DataFrame operations, and label-based selection. This chapter focuses on changing table structure without accidentally modifying the wrong object.
Add, transform, and sort
Assign a column with df["name"] = values. The values must align with the DataFrame's index. assign returns a new DataFrame, which is useful in chained transformations.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
df["pop_k"] = df["pop_m"] * 1000
result = (
df.assign(is_large=df["pop_m"] > 3)
.sort_values(["pop_m", "city"], ascending=[False, True])
)
print(result)
print(df.sort_index())sort_values sorts by column values. sort_index sorts by index labels. Neither operation changes the original unless you assign the result back or use inplace=True.
Copies and chained assignment
Filtering can produce an object whose relationship to the original is unclear. Avoid chained assignment such as df[df["pop_m"] > 3]["city"] = "Large". It may update a temporary object and raises warnings in many situations.
Use one .loc operation for an intentional in-place update:
df.loc[df["pop_m"] > 3, "city"] = "Large"Use .copy() when creating an independent working table:
large = df.loc[df["pop_m"] > 1].copy()
large["pop_k"] = large["pop_m"] * 1000Group, combine, and reshape
groupby splits rows into groups, and agg calculates summaries. concat stacks compatible tables. merge joins tables using matching key columns.
summary = (
df.groupby("region", as_index=False)
.agg(total_m=("pop_m", "sum"), n_cities=("city", "count"))
)
labels = pd.DataFrame({"region": ["EU"], "label": ["Europe"]})
joined = df.merge(labels, on="region", how="left")
wide = df.pivot_table(index="region", values="pop_m", aggfunc="mean")
long = wide.reset_index().melt(
id_vars="region", var_name="measure", value_name="value"
)A left merge preserves every row from its left table. A pivot table summarizes values into a report-like layout. melt converts columns into rows.
Choose suitable dtypes
A column's dtype controls how pandas stores its values. Convert repeated text values to category when the column has relatively few distinct values:
df["region"] = df["region"].astype("category")This can reduce memory use and improve some operations. Do not use category automatically for nearly unique text, where its category metadata may add overhead.
Exercise
Which operation safely edits only a filtered table?
Show answer
Create it with filtered = df.loc[mask].copy() before assigning columns.