Sub topic 2
Adding a column with df["name"] = ...
This chapter assumes you can build a DataFrame, select a column by name, and read basic Python. It covers the most common way to add a column: assigning to a new name.
The basic pattern
Assigning to a column name that does not exist yet creates that column. Assigning to a name that already exists replaces it.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df["total"] = df["price"] * df["qty"]
print(df)The right-hand side is a Series computed element by element across all rows. pandas stores it under the name "total", and the new column goes at the end of the frame. The operation changes df in place.
What you can assign
The right-hand side can take several forms:
| Right-hand side | Result |
|---|---|
| A scalar, such as `0` or `"new"` | Every row gets the same value |
| A Series | Values are matched to rows by index label |
| A list, array, or other sequence | Values are placed by position, and the length must equal the row count |
| An expression using other columns | Computed per row, as in the example above |
df["currency"] = "USD"
df["rank"] = [2, 1, 3]
print(df)Alignment by index
When you assign a Series, pandas aligns it to the DataFrame by index label, not by position. Rows with no matching label get NaN.
extra = pd.Series([100, 200], index=[0, 2])
df["bonus"] = extra
print(df["bonus"])Row 1 has no label in extra, so its bonus is NaN. This is useful when the index carries meaning. It surprises people when two frames have been filtered or sorted differently. If you want position-based assignment, pass .to_numpy() or a list instead.
df["bonus"] = extra.to_numpy().tolist() + [0]Common errors
- Length mismatch. Assigning a list or array of the wrong length raises
ValueError: Length of values does not match length of index. - Typos in the name. Writing
df["totl"] = ...silently creates a second column. Checkdf.columnswhen a result looks missing. - Attribute-style assignment.
df.total = ...sets a plain Python attribute and does not create a column. Use brackets for assignment. - Overwriting by accident. Reusing an existing name replaces the old column with no warning.
df.total2 = df["total"] * 2 # sets an attribute only
print("total2" in df.columns) # FalseWhy assignment mutates
Assignment changes the frame you hold. Any other variable that points to the same DataFrame sees the change.
alias = df
alias["flag"] = True
print("flag" in df.columns) # TrueIf you need an independent frame, call df.copy() first. Later chapters cover assign(), which returns a new frame, and the rules around copies and chained assignment.
Exercise
A DataFrame has the index [10, 11, 12]. You run df["x"] = pd.Series([1, 2, 3]). What values does column "x" contain, and why?
Show answer
All NaN. The Series has index [0, 1, 2], and none of those labels match the DataFrame's index [10, 11, 12]. Assignment of a Series aligns by label, not position. To assign by position, use a list or pass .to_numpy().
Exercise
Add a column "discounted" to the df above that holds price reduced by 10 percent.
Show answer
df["discounted"] = df["price"] * 0.9