← Back to Pandas Course | Chapter 6: Data Operations | Lesson 5 of 7

Arithmetic operations

Arithmetic on columns and DataFrames is element-wise and aligns on labels.

In this page:

  1. Arithmetic operations
Syntax
python
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

python
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
  1. Expecting positional alignment
  2. Ignoring NaN from mismatched labels
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.