Sub topic 11
Adding and transforming columns
This chapter assumes you can build a DataFrame, select with loc and boolean masks, and use vectorized arithmetic. Here you will add columns, transform existing ones, and avoid the bugs that come from assigning into slices.
Direct column assignment
Assigning to a new column name creates the column. The right-hand side can be a scalar, a list, or a Series. A Series is aligned to the DataFrame's Index by label, not by position.
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
df["source"] = "demo"
print(df)This changes df in place. A list must have the same length as the DataFrame, or pandas raises a ValueError.
Using assign for a new DataFrame
assign returns a new DataFrame with the extra columns and leaves the original unchanged. This suits method chains. Keyword names become column names, and a function receives the intermediate DataFrame, so later columns can use earlier ones.
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"],
})
out = df.assign(
pop_k=df["pop_m"] * 1000,
is_big=lambda d: d["pop_k"] > 3000,
)
print(out)
print("pop_k" in df.columns) # False, df is unchangedTransforming values
For simple transformations, prefer vectorized methods over Python loops. Use map to translate values through a dictionary, and where or numpy.select for conditions.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"region": ["EU", "SA", "AS", "EU"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
names = {"EU": "Europe", "SA": "South America"}
df["region_name"] = df["region"].map(names) # AS becomes NaN
df["size"] = df["pop_m"].where(df["pop_m"] > 3, 0) # keep if True, else 0
df["city"] = df["city"].str.upper()
print(df)map returns NaN for keys missing from the dictionary. Check for this before relying on the result.
Assigning to part of a column
To change only some rows, use a single loc call with the mask and the column together.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima"], "pop_m": [0.7, 10.7]})
df.loc[df["pop_m"] > 5, "pop_m"] = 11.0 # correct: one loc call
# df[df["pop_m"] > 5]["pop_m"] = 11.0 # chained: may change a temporary copy
print(df)The chained form first builds a filtered object and then assigns into it. That object may be a copy, so df may not change, and pandas may warn with SettingWithCopyWarning. A single loc call writes to df directly.
Common errors
- Assigning a Series with a different Index, which produces NaN where labels do not match.
- Assigning a list of the wrong length.
- Forgetting that
assigndoes not modifydf, so the result must be stored. - Chained assignment into a filtered subset.
Exercise
Given df with a numeric column pop_m, write one statement that sets pop_m to 0 for every row where pop_m is below 1, so that df itself changes.
Show answer
df.loc[df["pop_m"] < 1, "pop_m"] = 0. A single loc call with the mask and the column label writes directly into df, which avoids chained assignment.