Sub topic 1
Columns are Series: the building block
Prerequisites
Assume you can create a pandas DataFrame, select a column by name, and read basic Python expressions and lambdas. NumPy is helpful but not required.
A column is a Series
A pandas DataFrame is a table whose columns are Series objects. A Series is a one-dimensional, labeled sequence of values. Its index lets pandas align values by row when you combine columns.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
print(df["price"])df["price"] returns a Series. The column name is its label, and the row index identifies each value.
Adding a column with assignment
Assign an expression to a new column name:
df["total"] = df["price"] * df["qty"]
print(df)Pandas computes the multiplication element by element. The new total Series is aligned with the existing index and stored in the DataFrame. Assignment to an existing name replaces that column.
flowchart TD
A["price Series"] --> C["Vectorized multiplication"]
B["qty Series"] --> C
C --> D["total Series"]
D --> E["New DataFrame column"]Computing columns with vectorized operations
A vectorized operation applies an operation to an entire Series without an explicit Python loop. Arithmetic, comparisons, and many NumPy functions work this way.
df["is_bulk"] = df["qty"] >= 5
df["discounted"] = df["price"] * 0.9The comparison creates a Boolean Series. Operations between columns depend on index alignment. If two Series have different indexes, pandas matches their labels rather than simply pairing their physical positions.
Chaining column creation with `assign()`
assign() returns a new DataFrame, so it fits naturally in a method chain. Use a lambda when a new column depends on a column created earlier in the same call.
result = (
df.assign(
total=lambda d: d["price"] * d["qty"],
total_with_tax=lambda d: d["total"] * 1.2,
)
)
print(result)The original df is unchanged by assign(). Use direct assignment when mutation is clear and convenient. Use assign() when composing several transformations.
Exercise
Why does total_with_tax use a lambda in the assign() example?
Show answer
The lambda receives the DataFrame after total has been added, so it can use that new column.