Sub topic 8
Column names with spaces or reserved characters
This chapter covers what to do when a column name cannot be written as a Python keyword argument. I assume you can write assign calls with lambdas, as in the earlier chapters, and that you know basic groupby and agg. You should also know how Python's ** unpacking works for function calls, though the chapter reviews it briefly.
Why keyword arguments fail
assign takes new columns as keyword arguments. The argument name becomes the column name:
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"])
print(list(result.columns))
# ['order_id', 'region', 'price', 'quantity', 'revenue']A keyword argument name must be a valid Python identifier. An identifier has these properties:
- It contains only letters, digits, and underscores.
- It does not start with a digit.
- It is not a reserved word such as
class,from,if,in, orlambda.
Real data often breaks these rules. Spreadsheet exports give you names like unit price, net-price, 2024 sales, Revenue (USD), or % change. Writing df.assign(unit price=...) is a SyntaxError. Python rejects it before pandas runs, so no pandas option can fix it. The same happens with df.assign(class=...), because class is a keyword.
The fix: unpack a dictionary
Python lets you pass keyword arguments from a dictionary with **. The call f(**{"a": 1}) behaves like f(a=1). The dictionary keys are ordinary strings, so they can contain any characters. assign accepts arbitrary keyword arguments, so the unpacked keys become column names as they are.
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(**{"unit price": lambda d: d["revenue"] / d["quantity"]})
)
print(list(result.columns))
# ['order_id', 'region', 'price', 'quantity', 'revenue', 'unit price']The value is still a callable that receives the current DataFrame, so everything you learned about lambdas in assign still applies. Only the way you supply the name has changed. Inside the lambda, you read columns with d["revenue"]. Bracket access works for every column name.
You can mix both styles in one call. Python requires that the ** unpacking comes after the plain keywords:
result = df.assign(
revenue=lambda d: d["price"] * d["quantity"],
**{"revenue per unit": lambda d: d["revenue"] / d["quantity"]},
)Evaluation order follows the order you wrote the arguments, and a dictionary keeps its insertion order. This means a dictionary entry can use a column created by an earlier keyword argument, as revenue per unit does here.
Reading these columns in later steps
Creating the column is only half the problem. Later steps must also refer to it, and each chainable method has its own rules.
| Where you refer to the column | Works for odd names? | How |
|---|---|---|
| Lambda body | Yes | `d["unit price"]` |
| `query` string | Yes, with backticks | ``"`unit price` > 8"`` |
| `sort_values` | Yes | `sort_values("unit price")` |
| `groupby` keys | Yes | `groupby("unit price")` |
| Attribute access | No | `d.unit price` is a syntax error |
The query method evaluates a string as an expression, so a space would split the name in two. Wrapping the name in backticks tells query it is one column:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(**{"unit price": lambda d: d["revenue"] / d["quantity"]})
.query("`unit price` > 8")
.sort_values("unit price", ascending=False)
)
print(result[["order_id", "unit price"]])Three rows remain, for orders 2, 3 and 1, because order 4 has a unit price of 5.
Named aggregation has the same limit
agg with named aggregation is also keyword-based, so the same problem appears when you want readable output headers:
summary = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.groupby("region", as_index=False)
.agg(**{
"total revenue": ("revenue", "sum"),
"order count": ("order_id", "count"),
})
.sort_values("total revenue", ascending=False)
)
print(summary)Each key in the dictionary is the output column name, and each value is a (column, function) tuple.
Alternative: clean names inside, friendly names outside
Unpacking dictionaries makes a chain noisier. Many analysts avoid the problem by working with clean snake_case names throughout and renaming only at the end, when the table is presented:
raw = pd.DataFrame({
"Order ID": [1, 2],
"Unit Price": [10.0, 20.0],
"Qty": [2, 1],
})
clean = (
raw
.rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
.assign(revenue=lambda d: d["unit_price"] * d["qty"])
.rename(columns={"revenue": "Revenue (USD)"})
)
print(list(clean.columns))
# ['order_id', 'unit_price', 'qty', 'Revenue (USD)']The first rename receives a function, which pandas applies to every column label. This normalizes messy input names in one step at the top of the chain. The final rename converts to display names.
| Approach | Advantage | Cost |
|---|---|---|
| `assign(**{...})` | The exact name exists at every step | Extra syntax, and backticks in `query` |
| Clean names, rename at the end | Simple code in the middle of the chain | The final names appear only at the end |
Choose by where the odd name must exist. If it only matters in the final output, rename last. If the output feeds directly into an export or a library that expects specific headers, assign(**{...}) is fine. Normalizing at the start is usually the better default for data you import yourself.
Building names dynamically
The dictionary form also lets you compute column names, which keyword arguments cannot do. A common case is creating one column per item in a list:
months = ["jan", "feb"]
sales = pd.DataFrame({"jan": [1, 2], "feb": [3, 4]})
result = sales.assign(**{
f"{m} (doubled)": (lambda d, m=m: d[m] * 2) for m in months
})
print(list(result.columns))
# ['jan', 'feb', 'jan (doubled)', 'feb (doubled)']The m=m default argument is required. Python looks up the variable m in a lambda when the lambda is called, not when it is created. assign calls the lambdas after the comprehension has finished, so without m=m every lambda would see the last value of m, and both new columns would be copies of feb. A default argument captures the current value when each lambda is created. assign passes only one positional argument, the DataFrame, so the extra parameter is safe.
The same distinction explains why a callable matters here. If you wrote sales[m] * 2 directly as the value, pandas would compute it from the original sales before assign runs. That would not reflect earlier steps in a longer chain.
Common errors
SyntaxErroron a name with a space or dash. The name was written as a keyword argument. Move it into a**{...}dictionary.SyntaxErroron a reserved word such asclass. The cause is the same. A dictionary key like"class"is accepted.- A
queryerror mentioning a name fragment. An unquoted column name containing a space or symbol was passed toquery. Add backticks. - Attribute access that returns the wrong thing. A column called
size,count, ormaxis valid inassign(size=...), butd.sizereturns the DataFrame's element count, not your column. Used["size"]consistently for any name that could collide with a DataFrame attribute. - Duplicate-looking names.
"unit price"and"unit price"(two spaces) are different columns. If you receive imported files, normalize whitespace with therenamefunction shown earlier.
Summary of the working model
assignand namedaggtake their column names from Python keyword arguments, which must be valid identifiers.**{"any name": value}supplies the same arguments from a dictionary, so any string works as a name.- Bracket access (
d["name"]) works for every name. Attribute access and unquotedquerystrings do not. - Backticks make
querytreat a name with spaces or symbols as one column. - Computed names and lambdas built in a loop need
m=m-style default arguments to avoid late binding.
Exercise
A chain ends with .assign(net-price=lambda d: d["price"] * 0.8). What happens, and how do you fix it? Then write the step after it that keeps only rows where that column exceeds 10.
Show answer
Python raises a SyntaxError, because net-price is parsed as net - price and is not a valid keyword argument name. Supply the name from a dictionary: .assign(**{"net-price": lambda d: d["price"] * 0.8}). The filter needs backticks because query parses its string as an expression: .query("net-price > 10").
Exercise
You run sales.assign(**{f"{m} x2": (lambda d: d[m] * 2) for m in ["jan", "feb"]}). Both new columns contain the doubled feb values. Why, and what is the fix?
Show answer
The lambdas look up m when assign calls them, which is after the comprehension has finished, so every lambda sees the last value, "feb". Capture the value at creation time with a default argument: (lambda d, m=m: d[m] * 2).
Exercise
Write a chain over the df from this chapter that creates revenue, groups by region, produces columns named total revenue and order count, and sorts by total revenue from largest to smallest.
Show answer
summary = (df.assign(revenue=lambda d: d["price"] d["quantity"]).groupby("region", as_index=False).agg({"total revenue": ("revenue", "sum"), "order count": ("orderid", "count")}).sortvalues("total revenue", ascending=False)). The `*{...}` dictionary is needed because the output names contain spaces.