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

Comparison operations

Comparing columns or a whole DataFrame gives True/False answers you can count or filter with.

In this page:

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

python
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
  1. Using == to compare whole DataFrames for equality
  2. Comparing Series with different indexes
  3. 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:

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.