2. How can you filter and select Pandas DataFrame rows based on column values?
The fastest and most idiomatic way to filter rows in a Pandas DataFrame is **boolean indexing** (`df[df["column"] > value]`), which evaluates vectorized NumPy conditions at C speed. For complex multi-condition filters or dynamic expressions, **`df.query()`** provides cleaner, SQL-like readability.
## 1. Single & Multi-Condition Boolean Indexing
When combining multiple conditions in Pandas, you **must** wrap each condition in parentheses `(...)` and use bitwise operators (`&` for AND, `|` for OR, `~` for NOT) instead of Python's `and` / `or` keywords.
#python
import pandas as pd
df = pd.DataFrame({
"name": ["Ali", "Zara", "Bilal", "Ayesha"],
"score": [88, 95, 72, 91],
"city": ["Lahore", "Islamabad", "Lahore", "Karachi"]
})
# Single condition
high_scorers = df[df["score"] >= 90]
# Multiple conditions (parentheses are mandatory)
lahore_top = df[(df["score"] > 80) & (df["city"] == "Lahore")]
You must log in or register to comment.
