Raw tables often contain the quantities needed for analysis but not the derived values a report or export requires. pandas can calculate those values as new DataFrame columns without iterating over rows.
Bracket assignment writes one column at a time to the existing DataFrame. A scalar is broadcast to every row, while a Series or vectorized expression supplies one value per row; assigning a new label appends it to the column order.
Reusing an existing label replaces that column, and an assigned Series aligns by index label rather than row position. pandas 3 also rejects chained assignment for changes to a subset, so conditional updates must target the DataFrame in one statement.
Related: How to create a pandas DataFrame
Related: How to rename columns in pandas
Related: How to convert data types in pandas
import pandas as pd df = pd.DataFrame( { "item": ["notebook", "pencil", "eraser"], "qty": [3, 10, 5], "unit_price": [2.5, 0.4, 0.8], } )
df["line_total"] = df["qty"] * df["unit_price"]
df["currency"] = "USD"
pandas broadcasts the scalar string to every row.
df["bulk_order"] = df["qty"].ge(10)
Series.ge() returns one boolean per row, so this assignment avoids row-by-row loops and chained updates.
Related: How to migrate pandas code for Copy-on-Write
expected_columns = [ "item", "qty", "unit_price", "line_total", "currency", "bulk_order", ] assert df.columns.tolist() == expected_columns assert df["line_total"].tolist() == [7.5, 4.0, 4.0] assert df["currency"].eq("USD").all() assert df["bulk_order"].tolist() == [False, True, False] assert str(df["line_total"].dtype) == "float64" assert str(df["bulk_order"].dtype) == "bool" result_columns = ["item", "line_total", "currency", "bulk_order"] print(df[result_columns].to_string(index=False)) print() print("Dtypes:") print(df[["line_total", "bulk_order"]].dtypes)
A wrong column order, value, or dtype raises AssertionError before the table is printed.
$ python3 create_columns.py
item line_total currency bulk_order
notebook 7.5 USD False
pencil 4.0 USD True
eraser 4.0 USD False
Dtypes:
line_total float64
bulk_order bool
dtype: object