Sub topic 5
Adding columns with assign
This chapter covers DataFrame.assign, the method that adds or replaces columns without changing the original DataFrame. It assumes you can build a DataFrame, select columns, and write a lambda. It also assumes you know that most pandas methods return a new object, which the first chapters of this tutorial cover. Later chapters go deeper into callables, several dependent columns, and unusual column names. Here you learn what assign does, what you can pass to it, and the mistakes people make first.
All examples reuse this DataFrame.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 15.0, 5.0],
"quantity": [2, 1, 3, 10],
})What assign does
assign takes keyword arguments. Each keyword is a column name, and each value says what goes in that column. It returns a new DataFrame with those columns added or replaced.
with_revenue = df.assign(revenue=df["price"] * df["quantity"])
print(with_revenue)
print(list(df.columns)) order_id region price quantity revenue
0 1 east 10.0 2 20.0
1 2 west 20.0 1 20.0
2 3 east 15.0 3 45.0
3 4 west 5.0 10 50.0
['order_id', 'region', 'price', 'quantity']The last line shows that df still has its original four columns. assign never modifies the object it is called on. That is why it fits in a chain: each step takes a DataFrame and hands a new one to the next step.
Compared with bracket assignment
The usual way to add a column is bracket assignment.
df2 = df.copy()
df2["revenue"] = df2["price"] * df2["quantity"]This is a statement. It changes df2 in place and produces no value, so you cannot put it in the middle of a chain. It is also the source of SettingWithCopyWarning. If df2 came from a filter such as df[df["price"] > 5], pandas cannot always tell whether you are writing to a copy or to a view of the original data. assign avoids this because the result is always a new object that you own.
| Row | `df["x"] = ...` | `df.assign(x=...)` |
|---|---|---|
| Changes the original | Yes | No |
| Returns a DataFrame | No | Yes |
| Usable inside a chain | No | Yes |
| Column name | Any string | Must work as a keyword (see below) |
| Several columns at once | One per statement | Any number per call |
Neither style is wrong. Bracket assignment is fine for a quick change in a script. Use assign when the step belongs in a chain.
Adding versus replacing
If the keyword names a column that does not exist, assign appends it at the end. If the column already exists, assign replaces it and keeps its position.
result = df.assign(region=df["region"].str.upper())
print(result) order_id region price quantity
0 1 EAST 10.0 2
1 2 WEST 20.0 1
2 3 EAST 15.0 3
3 4 WEST 5.0 10Replacing a column also replaces its dtype. You can turn an integer column into a float column, or a string column into a category, by assigning the converted values. This makes assign a good place for type cleanup.
result = df.assign(
region=df["region"].astype("category"),
quantity=df["quantity"].astype("float64"),
)
print(result.dtypes)What you can pass as a value
Each keyword accepts four kinds of value.
- A scalar. It is repeated on every row.
- A Series. It is aligned to the DataFrame by index label.
- A list or NumPy array. It must have exactly one element per row, and it is matched by position.
- A callable. It is called with the DataFrame, and its return value is used. The next chapter covers this in detail.
result = df.assign(
currency="USD",
is_bulk=df["quantity"] >= 10,
rank=[3, 4, 2, 1],
)
print(result[["order_id", "currency", "is_bulk", "rank"]]) order_id currency is_bulk rank
0 1 USD False 3
1 2 USD False 4
2 3 USD False 2
3 4 USD True 1Series values align on the index
When you pass a Series, pandas matches its index labels against the DataFrame's index. Rows with no matching label get NaN. Row order in the Series does not matter.
discount = pd.Series([0.1, 0.2], index=[0, 3])
result = df.assign(discount=discount)
print(result[["order_id", "discount"]]) order_id discount
0 1 0.1
1 2 NaN
2 3 NaN
3 4 0.2This is usually what you want, because it keeps values attached to the right rows. It is a surprise when the index of your Series does not match for some other reason, such as a Series built from a filtered or re-indexed copy. Every row then becomes NaN with no error. If you want position-based matching instead, pass series.to_numpy() or a list.
Lists and arrays must match the length
A list or array is not aligned. It must have exactly as many elements as the DataFrame has rows.
try:
df.assign(rank=[3, 4, 2])
except ValueError as error:
print(error)Length of values (3) does not match length of index (4)The stale-reference mistake
The examples above write df["price"] inside the call. That reads the original df, not the DataFrame at the current point in a chain. The difference does not show up in a single call, but it causes bugs once you chain.
wrong = (
df
.assign(price=df["price"] * 2)
.assign(revenue=df["price"] * df["quantity"])
)
print(wrong[["price", "revenue"]]) price revenue
0 20.0 20.0
1 40.0 20.0
2 30.0 45.0
3 10.0 50.0The first step doubled the price, but the second step still reads the original df, so revenue is computed from the old prices. The expected revenues are 40, 40, 90, and 100. Nothing raises an error, and the numbers look plausible.
The fix is to pass a callable. assign calls it with the DataFrame as it exists at that step, and the lambda's parameter is a name for that DataFrame.
right = (
df
.assign(price=lambda d: d["price"] * 2)
.assign(revenue=lambda d: d["price"] * d["quantity"])
)
print(right[["price", "revenue"]]) price revenue
0 20.0 40.0
1 40.0 40.0
2 30.0 90.0
3 10.0 100.0Using d here, rather than df, also keeps the lambda from silently reading a variable defined outside the chain. The next chapter explains why this works and covers the rules for evaluation order.
Keyword names
The column name is a Python keyword argument, so it must be a valid identifier. assign(revenue=...) works. These do not.
# SyntaxError: a space is not allowed in a keyword argument name
df.assign(unit price=df["price"])
# TypeError: assign takes only keyword arguments
df.assign("revenue", df["price"] * df["quantity"])A column with a space, a dash, or a leading digit needs a different form, which a later chapter in this tutorial covers. Until then, use bracket assignment or rename for those names.
Cost and copying
assign makes a copy of the DataFrame every time it runs. In older pandas versions this copies the underlying data. With Copy-on-Write, the default in pandas 3.0 and an option in 2.x, the copy is deferred until one of the objects is modified, so a chain of assign calls costs little extra memory. For a very large DataFrame on an older setup, a long chain of assign calls can use noticeably more memory than a few in-place bracket assignments. Measure before you worry about it.
Quick checks
assignalways returns a new DataFrame. If you forget to keep the result, nothing is saved:df.assign(x=1)on its own line does nothing useful.- New columns appear at the end, in the order of the keyword arguments. Replaced columns keep their position.
- Series values align by index label, and lists and arrays match by position and must have the right length.
- A value computed from
df[...]inside a chain reads the original. A value computed fromlambda d: d[...]reads the current DataFrame.
Exercise
A colleague writes out = df.query("quantity > 1").assign(share=df["quantity"] / df["quantity"].sum()). The chain runs without an error. What is wrong with the share column, and how do you fix it?
Show answer
df["quantity"] refers to the original DataFrame, so the sum covers all four rows (16), not just the rows left after the filter. The Series is aligned on the index, so the values land on the right rows, but the shares of the filtered rows no longer add up to 1. The fix is to use a callable so the sum comes from the filtered data: .assign(share=lambda d: d["quantity"] / d["quantity"].sum()).
Exercise
Starting from df, write one expression that returns a new DataFrame in which region is upper case, a new column currency holds "EUR" on every row, and df itself is unchanged. What is the column order of the result?
Show answer
df.assign(region=df["region"].str.upper(), currency="EUR"). The result has the columns order_id, region, price, quantity, currency. region keeps its original position because it was replaced, and currency is appended at the end.
Exercise
You run df.assign(bonus=pd.Series([5, 6, 7, 8], index=[10, 11, 12, 13])) on a DataFrame whose index is 0 to 3. What do you get in the bonus column, and how would you assign the values by position instead?
Show answer
The Series index labels (10 to 13) do not match any row label (0 to 3), so every bonus value is NaN and no error is raised. To assign by position, pass the raw values: df.assign(bonus=pd.Series([5, 6, 7, 8]).to_numpy()), or pass the list [5, 6, 7, 8] directly.