Arithmetic operations
Arithmetic on columns and DataFrames is element-wise and aligns on labels.
In this page:
Syntax
df["column1"] + df["column2"]
df["column"] * scalar
df["column1"] / df["column2"]
Arithmetic operations
+, -, *, / and ** work between columns, scalars and whole DataFrames. Operations align on index and column labels, giving NaN where labels do not match. Methods such as add, sub, mul and div offer fill_value and axis control.
Note:
Use df.div(df.sum(axis=1), axis=0) to convert rows into proportions.
Example: Arithmetic operations
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df * 10)
print(df["a"] + df["b"])
print(df.div(df.sum(axis=1), axis=0))
# Output:
# a b
# 0 10 30
# 1 20 40
# 0 4
# 1 6
# dtype: int64
# a b
# 0 0.250000 0.750000
# 1 0.333333 0.666667
Related Topics
Common Mistakes
- Expecting positional alignment
- Ignoring NaN from mismatched labels
- Forgetting the axis argument
Chapter Summary
- Operators are element-wise
- Alignment uses labels
- add, sub, mul, div accept fill_value
- axis picks direction
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: