Knowledge base / Python
pandas assign: dependent columns and index alignment
I add dependent columns, explain lambda and distinguish Series label alignment from assigning a list in row order.

I want to add the weight of goods to a table, then calculate shipping weight including packaging. The second column depends on the first. DataFrame.assign supports this, provided I track which object supplies the data and when each new column becomes available.
The example uses two synthetic records and the behaviour documented for pandas 3.1.1. I focus on adding columns, dependencies between them and index alignment. These points cover the main traps needed to understand this focused method without turning the entry into a general pandas guide.
assign returns a new frame
DataFrame.assign is a method on a DataFrame object. Calling it pandas.assign is misleading when describing the actual invocation. Its result contains the original columns and the assigned ones. Reusing an existing name overwrites that column in the result.
I prepare the source:
import pandas as pd
base = pd.DataFrame(
{"units": [2, 3], "unit_weight": [10, 20]},
index=["A", "B"],
)
weighted = base.assign(weight=base["units"] * base["unit_weight"])
For A, weight is 2 times 10, giving 20. For B it is 3 times 20, giving 60. The weighted frame therefore has weight values of 20 and 60. The base frame still contains only units and unit_weight. Distinguishing these objects matters more than choosing particularly short variable names.
Put dependent columns in the right order
I add a synthetic packaging weight of 5 units to each shipment. Both derived columns can be created in one call:
result = base.assign(
weight=lambda x: x["units"] * x["unit_weight"],
shipped_weight=lambda x: x["weight"] + 5,
)
The supplied functions receive the frame being processed. The documentation confirms that later assignments may use columns created earlier within the same call. That is why weight appears before shipped_weight and the second function reads weight from x.
| Index | units | unit_weight | weight | shipped_weight |
|---|---|---|---|---|
| A | 2 | 10 | 20 | 25 |
| B | 3 | 20 | 60 | 65 |
A has shipping weight 20 plus 5; B has 60 plus 5. Row count and labels stay the same. Information is added to the existing observations, without aggregation or creation of extra shipments. The arithmetic can be followed directly from the two input records.
Why reading from base can produce KeyError
Creating weighted does not mean base gained a weight column. This is an intentional counterexample:
# Incorrect: base still has no weight column.
wrong = base.assign(shipped_weight=lambda x: x["weight"] + 5)
The function receives base, which lacks the required field. The repair is to use weighted as the input or combine the stages as above. I avoid adding an arbitrary column to base merely to conceal a mistake in the flow of objects.
Another trap is base.assign(weight=..., shipped_weight=base["weight"] + 5). The direct reference to base is evaluated before the method call runs. It cannot see the column that assign has yet to create. The Python reference describes argument evaluation. A lambda defers that calculation until pandas passes the appropriate frame into it.

A Series aligns by labels
An assigned Series carries its own index, unlike a list interpreted positionally. I reuse A and B in the opposite order:
extra = pd.Series([100, 200], index=["B", "A"])
aligned = base.assign(extra=extra)
Row A receives 200 and B receives 100. Matching labels determine placement, rather than the order in which the Series values were written. The pandas indexing guide explains alignment. If a frame label has no matching Series label, the result contains a missing value whose representation depends on the data type.
When I mean two values in row order, I use an explicit list of the correct length, such as base.assign(extra=[100, 200]). A then receives 100 and B receives 200. The choice should express the data’s intended relationship, rather than merely make a warning or an inconvenient blank disappear.
Scalars and existing names have straightforward meanings
The expression base.assign(batch="trial") places the same value on every row. This can describe a source or batch when the information genuinely applies to the entire set. The new column name comes from the keyword argument in the call.
To replace units with twice its value in a new result, I can write base.assign(units=lambda x: x["units"] * 2). The source retains 2 and 3, while the result has 4 and 6. An existing column name therefore signals a replacement in the returned object, rather than necessarily indicating an error.
A name containing a space can be supplied by unpacking a dictionary, for example base.assign(**{"batch label": "trial"}). I do not rename source fields unnecessarily, although for new data I prefer a simple convention that makes later steps easy to read. Naming and computation remain separate choices.
A new object does not guarantee a memory cost
When comparing assign with base["weight"] = ..., I emphasise program behaviour: assign returns a result, while direct assignment changes the named frame. Writing base = base.assign(...) replaces the reference held in the base variable. That also matters when following a longer example.
I do not describe a DataFrame as an immutable type or promise a full physical copy of every buffer. pandas has Copy-on-Write rules covered in its migration guide. Without measuring a specific process, I make no universal claim that either style is faster or uses less memory.
A function supplied to assign should not mutate the input frame. I use it to return a calculated value, without hidden writes to other columns. This keeps the flow understandable even when the operation appears inside a longer chain of transformations. Readability depends on explicit responsibilities as much as on compact syntax.
Exercise: identify the dependency’s source
Change packaging weight from 5 to 10 and work out the results manually: A should have 30 and B 70. Then explain why calling assign on base does not make weight available in base afterwards. The explanation should identify the object holding the returned result.
Finally, reverse the labels in extra while keeping its values and predict the difference between a Series and a list. For more on row labels, read about set_index. I check the input object, dependency order and index before looking for a more exotic explanation of an incorrect derived column.
Key takeaways
Does assign change the source frame?
It returns a new frame. Assigning that result to the same variable replaces its reference; calling the method alone does not add columns to the source.
How do I use a column created earlier in the same call?
Put its assignment first and use a callable, such as lambda x, that reads the current frame passed by pandas.
Why do Series values appear in a different order?
A Series aligns by index labels. A list of the correct length assigns values positionally.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
