Sub topic 2
Adding a column with df["name"] = ...
This chapter covers the basic way to add a column to a pandas DataFrame: assign to a column name that doesn't exist yet. It assumes you can build a DataFrame, select a column by name, and read basic Python. NumPy is not needed here. Later chapters cover assign(), conditional columns, and copy warnings in depth. This one explains what the assignment does and where it surprises people.
What the assignment does
df["total"] = ... is a call to DataFrame.__setitem__. pandas evaluates the right-hand side first. If the key is not an existing column, it adds a new column at the end. If the key exists, it replaces that column.
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) item price qty total
0 pen 1.5 10 15.0
1 book 12.0 3 36.0
2 lamp 30.0 2 60.0The expression df["price"] * df["qty"] produces a Series with the same index as df. Assignment stores that Series as the new column. The assignment changes df in place, and you don't need to reassign df.
The right-hand side can be one of several kinds of value, and each kind is handled differently.
| Right-hand side | Behavior |
|---|---|
| Scalar (`"USD"`, `0`, `None`) | Repeated for every row |
| Series | Matched to rows by index label |
| List, tuple, NumPy array | Matched by position, length must equal the row count |
| DataFrame (with a list of new names) | Columns copied in order |
Scalars and sequences
A scalar is broadcast, which means copied into every row.
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book", "lamp"], "qty": [10, 3, 2]})
df["currency"] = "USD"
df["discount"] = 0.0
df["code"] = ["P", "B", "L"]
print(df)The list assigned to code is placed by position: the first element goes to the first row. The length must match exactly.
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book", "lamp"]})
try:
df["code"] = ["P", "B"]
except ValueError as err:
print(err)This prints Length of values (2) does not match length of index (3). pandas refuses to guess how to fill the missing row. A length mismatch with a list is an error. A mismatch with a Series is not, as the next section shows.
Index alignment
When the right-hand side is a Series, pandas does not use position. It matches each row of the DataFrame to the Series entry with the same index label. Labels that have no match become NaN.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
})
bonus = pd.Series({0: 1, 2: 5})
df["bonus"] = bonus
print(df) item price bonus
0 pen 1.5 1.0
1 book 12.0 NaN
2 lamp 30.0 5.0Row 1 has no label in bonus, so it gets NaN. The column also changed from integer to float, because integers cannot hold NaN. The dtype (the data type of a column) follows from the result.
Alignment is the most common source of silent errors in this chapter's topic. It shows up when the DataFrame has a non-default index, for example after filtering, sorting, or set_index.
import pandas as pd
stock = pd.DataFrame({"qty": [10, 3, 2]}, index=["a", "b", "c"])
ranks = pd.Series([1, 2, 3]) # index is 0, 1, 2
stock["rank_aligned"] = ranks # labels differ: all NaN
stock["rank_values"] = ranks.to_numpy() # by position
stock["rank_list"] = [1, 2, 3] # by position
print(stock) qty rank_aligned rank_values rank_list
a 10 NaN 1 1
b 3 NaN 2 2
c 2 NaN 3 3No label in ranks matches a, b, or c, so rank_aligned is entirely NaN. No error or warning appears. If you want position-based assignment from a Series whose index doesn't match, use .to_numpy() or .values. If you want label-based assignment, leave the Series alone and check the result for unexpected NaN.
Overwriting an existing column
Assigning to an existing name replaces the whole column. The new column does not need the same dtype as the old one.
import pandas as pd
df = pd.DataFrame({"qty": [10, 3, 2]})
print(df["qty"].dtype) # int64
df["qty"] = df["qty"] * 1.5
print(df["qty"].dtype) # float64Overwriting is useful for cleaning a column in place. It also destroys the original values. If you may need them again, write to a new name, such as qty_clean, and drop the old column later.
Assigning several columns at once
A list of names on the left takes a DataFrame on the right. Columns are matched in order, not by name.
import pandas as pd
df = pd.DataFrame({"price": [1.5, 12.0], "qty": [10, 3]})
df[["price_x2", "qty_x2"]] = df[["price", "qty"]] * 2
print(df)The first new name receives the first column of the right-hand DataFrame, and the second name receives the second. The names on the right don't need to match the names on the left. This is convenient but easy to get wrong when the column order changes, so check the order when you use it.
Names that need brackets
Always use brackets and a string to create a column. Attribute access can read an existing column (df.price), but it cannot create one.
import warnings
import pandas as pd
df = pd.DataFrame({"price": [1.5, 12.0]})
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
df.total = df["price"] * 2
print("total" in df.columns) # False
print(caught[0].category.__name__)pandas stores total as a plain Python attribute on the object, not as a column, and emits a UserWarning. Attribute access also fails for names with spaces ("unit price") and for names that match DataFrame methods or attributes such as count, index, or T. Bracket access works for every name.
Assigning only some rows
Assignment with .loc and a row mask can also create a new column. Rows outside the mask get NaN.
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book", "lamp"], "qty": [10, 3, 2]})
df.loc[df["qty"] > 2, "bulk"] = True
print(df) item qty bulk
0 pen 10 True
1 book 3 True
2 lamp 2 NaNThe column now mixes True and NaN, so its dtype is object, not bool. If you need a real boolean column, compute it from the comparison directly: df["bulk"] = df["qty"] > 2. That gives False for the third row, not NaN.
Common errors
- A list of the wrong length. Raises
ValueError. Checklen(values) == len(df). - All
NaNafter assigning a Series. The indexes don't share labels. Reset the index on one side, or assign.to_numpy()if position is what you want. - Integer column became float. A missing value was introduced. Use a nullable type such as
"Int64"if you need to keep integers with gaps. - Column not created. You used attribute assignment (
df.name = ...). Usedf["name"] = .... - Duplicate index labels. Assigning a Series whose index has repeated labels to a DataFrame can raise
ValueError: cannot reindex on an axis with duplicate labels. Deduplicate the index or assign by position.
Exercise
A DataFrame df has the index labels ["x", "y", "z"]. You run df["score"] = pd.Series([90, 80, 70]) and every value in score is NaN. Explain why, and give two different ways to fix it so that 90, 80, 70 are assigned to rows x, y, z in that order.
Show answer
The Series has the default index 0, 1, 2. Assignment aligns by label, and none of 0, 1, 2 match x, y, z, so every row gets NaN. Fix 1: assign a list, df["score"] = [90, 80, 70], which is placed by position. Fix 2: assign the array values, df["score"] = pd.Series([90, 80, 70]).to_numpy(), or give the Series the matching index: pd.Series([90, 80, 70], index=df.index).
Exercise
You write df.loc[df["qty"] > 2, "bulk"] = True and then find that df["bulk"].dtype is object. Write a one-line replacement that produces a bool column without NaN.
Show answer
df["bulk"] = df["qty"] > 2. The comparison returns a boolean Series for every row, so rows that fail the test get False instead of NaN, and the dtype stays bool.