Add calculated columns
Derive measurements or labels from existing columns.
Pandas · Module
DataFrame.assign creates or replaces columns and returns a new DataFrame containing the original columns plus the results. Values may be direct data or callables evaluated against the DataFrame.
DataFrame.assign returns a new DataFrame containing the original columns plus columns named by the keyword arguments. Each value can be computed from the DataFrame with a callable or assigned directly from a Series, scalar, or array-like value; keyword arguments are processed in order.
DataFrame.assign(**kwargs)| Name | Type | Description |
|---|---|---|
**kwargs | callable, Series, scalar, array-like, or dict | Column names are keywords. Values may be callable, Series, scalar, or array-like; callables are evaluated with the DataFrame and direct values are assigned. |
DataFrame: A new DataFrame with the new columns in addition to all the existing columns.
import pandas as pd
df = pd.DataFrame({"temp_c": [17.0, 25.0]})
result = df.assign(
temp_f=lambda frame: frame["temp_c"] * 9 / 5 + 32,
label=lambda frame: frame["temp_f"].round(1).astype(str) + " °F",
)
print(result)Creates two derived columns; the second callable uses the column created earlier in the same assign call.
Derive measurements or labels from existing columns.
Build a sequence of transformations where later results use earlier results.
Replace selected columns while retaining the rest of the DataFrame.
assign accepts keyword arguments whose names become column names. Callable values receive the DataFrame, while non-callable values such as Series, scalars, or arrays are assigned directly. The method returns a new DataFrame rather than modifying the original.
Follow-up: How can one derived column depend on another created in the same call? Place the dependent expression after the first keyword argument; assignment is evaluated in keyword order.
Multiple columns can be supplied in one assign call. Each keyword names a resulting column, and an existing column with the same name is overwritten in the returned object.
Follow-up: What restriction applies to callable values? They must not mutate the input DataFrame, even though pandas does not check for mutation.
Later keyword expressions can refer to columns created or modified earlier in the same call because items are computed and assigned sequentially. This enables concise dependent transformations.
Follow-up: What happens to the source DataFrame? It remains unchanged because assign returns a new DataFrame containing the added or replaced columns.
pandas.DataFrame.evalpandas.DataFrame.pipepandas.DataFrame.insert