Sub topic 5
Adding columns with assign
This chapter assumes you can build a DataFrame, select columns, and write a basic Python function. Earlier chapters showed that pandas methods return new DataFrames, which is what makes chaining possible. Here you learn the method that adds columns inside a chain: assign.
The problem with column assignment in a chain
The usual way to add a column is a statement:
df["revenue"] = df["price"] * df["quantity"]This changes df in place and returns nothing. Because it is a statement and not a method call, it cannot sit in the middle of a chain. It also overwrites your original data, so you cannot go back to the DataFrame as it was.
assign does the same job as a method. It returns a new DataFrame with the column added and leaves the original unchanged.
Basic usage
Each keyword argument of assign becomes a column. The keyword is the column name and the value is the data.
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],
})
with_revenue = df.assign(revenue=df["price"] * df["quantity"])
print(with_revenue)
print(list(df.columns))The first print shows five columns, including revenue. The second shows only the four original columns, which confirms that df was not modified.
What you can pass as a value
The value can be several things:
| Value | Result |
|---|---|
| A Series with a matching index | The column takes those values, aligned by index |
| A scalar such as `"web"` or `0` | Every row gets that value |
| A list or array of the right length | The values are used by position |
| A callable | Pandas calls it with the DataFrame and uses the result (next chapter) |
tagged = df.assign(channel="web", discount=0.0)
print(tagged)Replacing an existing column
If the keyword matches an existing column, assign replaces that column. No error or warning appears.
doubled = df.assign(price=df["price"] * 2)
print(doubled["price"].tolist())This prints [20.0, 40.0, 30.0, 10.0]. The original df["price"] still holds the old values. Replacing a column is a common way to clean data inside a chain, for example converting a text column to numbers or lowercasing a string column.
Where assign sits in a chain
Because assign returns a DataFrame, you can call another method on the result:
result = (
df
.assign(revenue=df["price"] * df["quantity"])
.sort_values("revenue", ascending=False)
)
print(result)A limit of passing values directly
Passing df["price"] * df["quantity"] works only when df is the DataFrame you want to compute from. Inside a longer chain that is often not true. Suppose you filter rows first:
result = (
df
.query("quantity > 1")
.assign(revenue=df["price"] * df["quantity"])
)Here df still refers to the original four rows, not the filtered three. Pandas aligns the new Series by index, so the result may look plausible while being computed from the wrong object. The next chapter shows how a callable fixes this by receiving the current DataFrame in the chain.
Keyword names
Keyword arguments must be valid Python identifiers. revenue works, but unit price does not. A later chapter covers how to handle names like that.
Exercise
Given the DataFrame df above, write an expression that returns a new DataFrame with a column named "is_bulk" set to True for every row, and a column "price" replaced by its value rounded to the nearest integer. After running it, what does df["price"].tolist() show?
Show answer
Use df.assign(is_bulk=True, price=df["price"].round()). The call returns the new DataFrame. Afterward df["price"].tolist() still shows [10.0, 20.0, 15.0, 5.0], because assign does not modify df.