Comparison operations
Comparing columns or a whole DataFrame gives True/False answers you can count or filter with.
In this page:
Syntax
df["column"] > value
df["column1"] == df["column2"]
(df["column"] > value).sum()
Comparison operations
Operators like ==, !=, > and < return boolean objects of the same shape. Summing a boolean Series counts the True values, and mean gives a proportion. eq, ne, gt and lt are method forms, and equals checks whole-object equality.
Note:
(df["a"] > 1).mean() gives the fraction of rows above 1.
Example: Comparison operations
import pandas as pd
df = pd.DataFrame({"a": [1, 5, 9], "b": [2, 5, 7]})
print(df["a"] > df["b"])
print((df["a"] > 3).sum(), (df["a"] > 3).mean().round(2))
print(df.equals(df.copy()))
# Output:
# 0 False
# 1 False
# 2 True
# dtype: bool
# 2 0.67
# True
Related Topics
Common Mistakes
- Using == to compare whole DataFrames for equality
- Comparing Series with different indexes
- Forgetting True counts as 1
Chapter Summary
- Comparisons return boolean objects
- sum counts True values
- mean gives the proportion
- equals tests full equality
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: