Sub topic 11
Adding and transforming columns
This chapter assumes you can build a DataFrame, select columns with [], and use loc with boolean masks. It also assumes you know that arithmetic on Series is vectorized and matches values by Index label. You will now create new columns, change existing ones, and avoid the usual errors.
Assigning a column with []
Assigning to a column name that does not exist creates the column. Assigning to one that exists replaces it.
import pandas as pd
orders = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [2.5, 12.0, 30.0],
"qty": [4, 1, 2],
})
orders["total"] = orders["price"] * orders["qty"]
orders["currency"] = "EUR" # a scalar is broadcast to every row
print(orders)The right-hand side can be a Series, a scalar, or a list-like value. A scalar is repeated for every row. A list, NumPy array, or other sequence must have exactly as many elements as the DataFrame has rows. Otherwise pandas raises a ValueError about a length mismatch.
This statement modifies orders in place. Every other reference to the same object sees the change.
Assignment aligns on the Index
A Series on the right-hand side is not matched by position. It is matched to the DataFrame by Index label, the same rule as in arithmetic.
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book", "lamp"]}) # index 0, 1, 2
extra = pd.Series([100, 200], index=[2, 0])
df["stock"] = extra
print(df)
# row 0 -> 200.0, row 1 -> NaN, row 2 -> 100.0Row 1 has no label in extra, so it gets NaN. That also forces the column to float64. If you really want positional assignment, pass extra.to_numpy() or extra.values. Do that only when you are sure the order is right.
Creating columns with assign
assign returns a new DataFrame with the added columns and leaves the original unchanged. That makes it a good fit for method chains. Keyword arguments are evaluated in order, so a later column can use an earlier one if you pass a function.
import pandas as pd
orders = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [2.5, 12.0, 30.0],
"qty": [4, 1, 2],
})
result = orders.assign(
total=lambda d: d["price"] * d["qty"],
tax=lambda d: d["total"] * 0.25,
)
print(result)
print("total" in orders.columns) # False, orders is unchangedThe lambda receives the DataFrame as it exists at that step, including total. Without a lambda, d["total"] would refer to a column that the original DataFrame does not have yet.
| Situation | Prefer |
|---|---|
| A quick edit in a script or notebook | `df["col"] = ...` |
| A chain of steps that should not mutate the input | `df.assign(col=...)` |
| A column name that is not a valid Python identifier | `df["my col"] = ...` |
| A specific column position | `df.insert(loc, name, value)` |
assign takes keyword arguments, so names such as "my col" need df.assign(**{"my col": ...}). Plain bracket assignment is simpler for those.
Choosing a transformation method
Most column transformations fall into a few categories. Pick the most specialized tool first. It is usually faster and clearer.
Conditions and lookups
import numpy as np
import pandas as pd
orders = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [2.5, 12.0, 30.0],
"qty": [4, 1, 2],
})
orders["total"] = orders["price"] * orders["qty"]
orders["size"] = np.where(orders["total"] >= 50, "large", "small")
orders["kind"] = orders["item"].map({"pen": "stationery", "book": "media"})
orders["label"] = orders["item"].str.upper()
print(orders)np.where(condition, a, b) picks a where the condition is true and b elsewhere. For more than two outcomes, use np.select with a list of conditions and a list of results.
map with a dictionary returns NaN for any value that is not a key. Here, lamp gets NaN in kind. This is often what you want, but it is also a common source of silent missing data. After a map, check orders["kind"].isna().sum().
replace differs from map on this point. It changes only the values it finds and leaves the rest as they were.
Updating only some rows
Use loc with a mask to write to selected rows of a column.
import pandas as pd
orders = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"qty": [4, 1, 2],
})
orders.loc[orders["qty"] > 1, "discount"] = 0.1
print(orders) # discount is NaN where qty <= 1
orders["discount"] = orders["discount"].fillna(0.0)
print(orders["discount"].tolist()) # [0.1, 0.0, 0.1]When the column does not exist, rows outside the mask are filled with NaN. Writing to one column in a single loc call is the safe form. The next chapter explains why df[mask]["col"] = value can silently fail.
apply as a last resort
Series.apply(func) calls a Python function once per element. That is much slower than a vectorized expression on large data, because the loop runs in Python instead of compiled code. Use it only when no vectorized equivalent exists, for example for custom parsing logic.
import pandas as pd
s = pd.Series(["10 kg", "3 kg", "7 kg"])
print(s.apply(lambda text: int(text.split()[0])).tolist()) # [10, 3, 7]
print(s.str.split().str[0].astype(int).tolist()) # same result, vectorizedThe second form uses the str accessor and is usually the better choice.
Changing types, names, and position
Transforming a column often means converting its dtype. astype returns a new Series that you assign back.
import pandas as pd
df = pd.DataFrame({"id": ["1", "2", "3"], "qty": [4, 1, 2]})
df["id"] = df["id"].astype(int)
df["qty"] = df["qty"].astype("float64")
df.insert(0, "row_label", ["a", "b", "c"]) # insert at position 0
df = df.rename(columns={"qty": "quantity"})
df = df.drop(columns=["row_label"])
print(df.dtypes)astype raises an error if a value cannot be converted. For messy text, pd.to_numeric(series, errors="coerce") turns bad values into NaN instead. insert raises an error if the column name already exists, unless you pass allow_duplicates=True. rename and drop return new DataFrames, so you must assign the result.
Common errors
- Length mismatch: assigning a list of the wrong length raises
ValueError. Checklen(values) == len(df). - Unexpected
NaN: a Series with a different Index, or amapdictionary missing some keys, produces missing values. Inspect the Index and count the missing values. - Forgotten assignment:
df.rename(...)anddf.assign(...)do not changedf. Assign the result to a name. - Attribute-style assignment:
df.total = ...does not create a column. It sets a plain Python attribute on the object. Always usedf["total"] = .... - Silent dtype change: introducing
NaNinto an integer column converts it tofloat64.
Exercise
Given df = pd.DataFrame({"a": [1, 2, 3]}) with the default index, you run df["b"] = pd.Series([10, 20], index=[1, 2]). What are the values in column b, and what is its dtype?
Show answer
The values are NaN, 10.0, 20.0. Series assignment aligns on Index labels. Label 0 is missing from the right-hand Series, so row 0 gets NaN, row 1 gets 10, and row 2 gets 20. The NaN forces the dtype to float64.