Sub topic 8
Column names with spaces or reserved characters
This chapter assumes you can use assign with lambdas, as covered in the earlier chapters on assign. It also assumes you know basic Python dictionaries and the ** unpacking syntax.
Why keyword arguments are not enough
So far you have written assign(revenue=lambda d: ...). The column name revenue is a keyword argument, so it must be a valid Python identifier. It cannot contain spaces or hyphens. It cannot start with a digit. It cannot be a reserved word such as class or lambda.
Real data often breaks these rules. Spreadsheet exports have headers like Unit Price or net-revenue. All of the following lines are syntax errors:
.assign(unit price=...)
.assign(net-revenue=...)
.assign(class=...)Python rejects these before pandas sees them, so no pandas option can fix them. You need another way to pass the name.
Unpacking a dictionary into assign
A call such as f(a=1) is equivalent to f(**{"a": 1}). A dictionary key is an ordinary string, so it can contain any characters. This lets you pass any name to assign:
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],
})
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(**{"unit price": lambda d: d["revenue"] / d["quantity"]})
)
print(result)The dictionary has one key, "unit price", and the value is a lambda. assign treats it exactly like a keyword argument. The lambda receives the current DataFrame, which already contains revenue because the earlier assign ran first.
You can put several entries in one dictionary. Ordinary keyword arguments can sit beside it:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(
**{
"unit price": lambda d: d["revenue"] / d["quantity"],
"net-revenue": lambda d: d["revenue"] * 0.8,
},
flag=True,
)
)Entries are evaluated in order. A later entry can use a column created by an earlier one, as with normal keyword arguments.
Using such columns later in the chain
Inside a lambda, use bracket access: d["unit price"]. Attribute access like d.unit price is not valid syntax. Even for names without spaces, attribute access fails if the name collides with a DataFrame method, such as a column called count.
The query method takes a string, so it needs another convention. Wrap the awkward name in backticks:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(**{"unit price": lambda d: d["revenue"] / d["quantity"]})
.query("`unit price` > 5")
)
print(result)Backticks work for names with spaces and for many punctuation characters. If a name is too unusual for query, filter with a boolean mask inside a lambda instead: .loc[lambda d: d["unit price"] > 5].
Renaming as an alternative
If the awkward names come from a source file, it is often cleaner to fix them once at the start of the chain. That way every later step uses plain identifiers:
raw = pd.DataFrame({"Unit Price": [10.0, 20.0], "Order Qty": [2, 1]})
clean = (
raw
.rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
.assign(revenue=lambda d: d.unit_price * d.order_qty)
)
print(clean)Here rename receives a function that is applied to every column name. You can then use keyword arguments and attribute access freely.
| Situation | Approach |
|---|---|
| Names come from data you read | Normalize with `rename` early in the chain |
| Output must keep spaces for a report | Use `assign(**{...})` |
| Filtering on a spaced name | Backticks in `query`, or a lambda with `loc` |
Exercise
You need to add a column named "total cost" to df, equal to price times quantity, and then keep only rows where it is above 20. Write the chain.
Show answer
result = (df.assign(*{"total cost": lambda d: d["price"] d["quantity"]}).query("total cost > 20")). The dictionary unpacking is needed because "total cost" is not a valid keyword name, and the backticks let query parse the name with a space.