DataFrame Basics
Add Derived Column
Compute a new column elementwise by looping over two parallel value lists and
appending each product. With pandas, a single vectorized expression
df['price'] * df['qty'] produces all products at once, and df.assign
attaches the result as a new column without mutating the original DataFrame.
By hand
With pandas
df.assign(total=df['price'] * df['qty']) multiplies the two Series
elementwise (index-aligned) and returns a new DataFrame with the total
column appended. The snapshot shows the input columns, then the new column as
a Series.
naive.py
price = [10, 25, 5, 20]
qty = [3, 2, 8, 1]
total = []
for i in range(len(price)):
total.append(price[i] * qty[i])
print('RESULT:', total)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
price = [10, 25, 5, 20]
qty = [3, 2, 8, 1]
df = pd.DataFrame({'price': price, 'qty': qty})
df2 = df.assign(total=df['price'] * df['qty'])
col = df2['total']
print('price:', df['price'].tolist())
print('qty:', df['qty'].tolist())
print('index:', col.index.tolist())
print('values:', col.tolist())
print('dtype:', col.dtype)
print('RESULT:', col.tolist())
price: [10, 25, 5, 20]
qty: [3, 2, 8, 1]
index: [0, 1, 2, 3]
values: [30, 50, 40, 20]
dtype: int64
RESULT: [30, 50, 40, 20]
Implementation notes
df.assignreturns a new DataFrame with the added column; the originaldfis unchanged. This makes it safe to chain:df.assign(...).assign(...).df['price'] * df['qty']is vectorized column arithmetic — the same broadcast-and-apply pattern as NumPy elementwise multiplication (seeelementwise-productin python-numpy ch03), applied to Series aligned by index label.- To add the column in-place instead, use
df['total'] = df['price'] * df['qty']. Preferassignin pipelines; prefer direct assignment for one-off mutations. - Cross-reference:
add-derived-field(python-data-basics) for the pure-Python dict version;elementwise-product(python-numpy ch03) for the NumPy array version.