pandas · difficulty ◆◆
pandas assign() — add derived columns without touching the original
assign() returns a new frame with your computed columns, so it drops into a chain instead of breaking it — and the lambda sees the frame it is building.
df.assign(inplace=True) never raises. It adds a boolean column literally named inplace — I have the output to prove it.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ df.assign()- 0.16.0 · 2015-03-22
- introduced in pandas
- (self, **kwargs)
- signature
- dplyr's mutate
- came from
- always on since 3.0
- Copy-on-Write
first bullet of the v0.16.0 release-note highlights; tracked as GH #9229
inspect.signature() on pandas 3.0.3 — one variadic parameter, no axis, no inplace
the 0.16.0 whatsnew names the R verb it was ported from
the copy_on_write option is deprecated because it can no longer be disabled — assign's copy costs metadata, not data
What it does
assign() adds columns to a DataFrame and hands back a new object: every original column stays, a reused name gets overwritten, and the frame you called it on is never modified. Each keyword argument is a column name; each value is a scalar, an array, a Series, or a callable. The callable branch is the part that earns assign its place: pandas hands it the frame it is currently building, evaluated in keyword order, so a column defined first is already visible to the next keyword in the same call. There is no inplace parameter and no axis — one variadic **kwargs, nothing else.
Why it matters
df['revenue'] = df['units'] * df['unit_price'] is a statement: it mutates your frame, and it cannot be written mid-pipeline. assign is that same derivation expressed as a step, which is why a real job turns into one readable expression — read_csv, clean the labels, add the money columns, filter, write parquet. And because the lambda receives the intermediate frame, a group total computed with transform() can be broadcast back onto the rows and divided out in the same call: share-of-region percentages without a merge and without a helper column.
Example
$ sales = pd.DataFrame({
"city": ["Vienna", "Graz", "Linz", "Salzburg", "Innsbruck"],
"units": [120, 45, 300, 88, 12],
"unit_price": [19.90, 24.50, 9.99, 15.00, 129.00],
})
report = sales.assign(
revenue=lambda d: (d["units"] * d["unit_price"]).round(2),
vat=lambda d: (d["revenue"] * 0.20).round(2),
)
print(report) city units unit_price revenue vat
0 Vienna 120 19.90 2388.0 477.6
1 Graz 45 24.50 1102.5 220.5
2 Linz 300 9.99 2997.0 599.4
3 Salzburg 88 15.00 1320.0 264.0
4 Innsbruck 12 129.00 1548.0 309.6One call, two derived columns — and vat reads revenue, which the previous keyword had just created. sales itself still has only three columns afterwards.
$ raw = pd.DataFrame({
"city": [" vienna ", "GRAZ", "linz ", " Salzburg", "innsbruck"],
"revenue": [2388.00, 1102.50, 2997.00, 1320.00, 1548.00],
})
clean = (raw
.assign(city=lambda d: d["city"].str.strip().str.title())
.assign(tier=lambda d: pd.cut(d["revenue"], bins=[0, 1500, 2500, 5000],
labels=["S", "M", "L"]))
.sort_values("revenue", ascending=False))
print(clean)
print(clean.dtypes) city revenue tier
2 Linz 2997.0 L
0 Vienna 2388.0 M
4 Innsbruck 1548.0 M
3 Salzburg 1320.0 S
1 Graz 1102.5 S
city str
revenue float64
tier category
dtype: objectThe messy-CSV opener I do every time: normalise the label in one assign, bucket the number in the next, sort. tier comes out as a real pandas category dtype, not object strings.
$ orders = pd.DataFrame({
"region": ["West", "West", "East", "East", "East", "North"],
"city": ["Vienna", "Innsbruck", "Graz", "Linz", "Salzburg", "Bremen"],
"revenue": [2388.00, 1548.00, 1102.50, 2997.00, 1320.00, 640.00],
})
share = (orders
.assign(region_total=lambda d: d.groupby("region")["revenue"].transform("sum"))
.assign(share=lambda d: (d["revenue"] / d["region_total"]).round(3))
.sort_values(["region", "share"], ascending=[True, False]))
print(share) region city revenue region_total share
3 East Linz 2997.0 5419.5 0.553
4 East Salzburg 1320.0 5419.5 0.244
2 East Graz 1102.5 5419.5 0.203
5 North Bremen 640.0 640.0 1.000
0 West Vienna 2388.0 3936.0 0.607
1 West Innsbruck 1548.0 3936.0 0.393Per-group stat inline: transform('sum') broadcasts 5419.5 back onto every East row, so the divide needs no merge and no join key. This is the pattern that replaces half my SQL window functions.
$ sales = pd.DataFrame({
"city": ["Vienna", "Graz", "Linz", "Salzburg", "Innsbruck"],
"units": [120, 45, 300, 88, 12],
"unit_price": [19.90, 24.50, 9.99, 15.00, 129.00],
})
print(sales.assign(revenue=1, inplace=True))
print("---")
print(sales.assign(prev_month=pd.Series([100.0, 200.0], index=[0, 9]))) city units unit_price revenue inplace
0 Vienna 120 19.90 1 True
1 Graz 45 24.50 1 True
2 Linz 300 9.99 1 True
3 Salzburg 88 15.00 1 True
4 Innsbruck 12 129.00 1 True
---
city units unit_price prev_month
0 Vienna 120 19.90 100.0
1 Graz 45 24.50 NaN
2 Linz 300 9.99 NaN
3 Salzburg 88 15.00 NaN
4 Innsbruck 12 129.00 NaNTwo silent failures in one snippet. inplace=True is not a flag, it's a column — all-True. And a Series aligns on the index, so labels 1-4 that don't exist in [0, 9] become NaN instead of erroring.
Common flags
- df.assign(revenue=...)
- Every keyword is a column name; an existing column of that name gets overwritten in the returned copy.
- lambda d: d['units'] * d['unit_price']
- Callable form — pandas passes the frame it is building, not the frame you called assign on.
- df.assign(a=1, b=lambda d: d['a'] + 1)
- kwargs evaluate in order (Python 3.7+ insertion order), so later columns can use earlier ones from the same call.
- df.assign(**{'unit price': 9.99})
- Names with spaces, dashes or Python keywords need the **dict form — the only escape hatch there is.
- df.assign(prev=series)
- Series and arrays assign positionally-by-index: misaligned labels give NaN, not an error.
- df.assign(share=lambda d: d['rev'] / d.groupby('g')['rev'].transform('sum'))
- Per-group stats inline — transform broadcasts the group total back to row level.
- df.pipe(f).assign(...)
- It composes: assign, query, pipe, groupby. Returning a new frame is what makes the chain possible.
History
0.16.0, 22 March 2015 — the dplyr port
assign is the first bullet under Highlights in the pandas 0.16.0 release notes, tracked as GH #9229, and the entry says it out loud: "Inspired by dplyr's mutate verb, DataFrame has a new assign method. The function signature for assign is simply **kwargs." Eleven years and a Copy-on-Write rewrite later, that signature is unchanged — inspect.signature on pandas 3.0.3 still prints (self, **kwargs).
Design note: a copy on the way in, order on the way through
The implementation is a shallow copy of the frame plus a loop: for each keyword, in order, resolve the value (call apply_if_callable if it's a callable) and set it as a column on that copy. That one decision explains three things you'll meet in practice — your original frame is untouched, a lambda sees the columns added earlier in the same call, and a lambda that mutates the frame it was handed leaks its column into the result. The docstring flags that last case in parentheses: the callable "must not change input DataFrame (though pandas doesn't check it)".
Under the hood
Under the hood: a shallow copy and a kwargs loop
No expression compiler, no Cython kernel. assign makes a shallow copy of the frame, then walks your keywords in order calling pandas' apply_if_callable(value, data) and setting the outcome as that column on the copy. Since the copy is shallow — and since pandas 3.0 has Copy-on-Write permanently on — nothing materialises until a block is actually written, so five chained assigns are five cheap frames over the same data, not five copies of your two million rows. The vectorised work happens inside your lambda (that multiply is a numpy op; .str.strip() runs in the string kernel). assign stays a thin, predictable wrapper, which is exactly why the ordering guarantee you rely on comes from Python's ordered kwargs rather than from pandas.
Fun facts
Pros & cons
pros
- + Chained by construction: returns a new frame, so read → clean → derive → filter stays one expression
- + Lambdas see the frame as it is being built — vat can use revenue from the same call, no temp variables
- + Takes anything: scalar, numpy array, Series or callable — and group stats via transform() fit right in
cons
- − No inplace and no axis — a stray inplace=True becomes a column instead of raising an error
- − Every keyword is a column name, so names with spaces or Python keywords force the uglier **{...} dict form
- − The 'don't mutate the input frame' contract is documented but unchecked — a mutating lambda adds columns to your result
Takeaways
- 1Use assign() when the derivation is a pipeline step: df['x'] = ... is a statement and cannot live inside a method chain.
- 2Keyword order is evaluation order — define revenue before vat and the second lambda can read the first column in the same call.
- 3Spaces, dashes or reserved words in a column name mean .assign(**{'unit price': ...}); there's no other syntax.
- 4Put per-group maths inline: .assign(share=lambda d: d['rev'] / d.groupby('region')['rev'].transform('sum')) beats a merge.
- 5assign never mutates and has no inplace flag — if you passed one, you just created a column called inplace.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
