Skip to main contentSkip to solution

Given a DataFrame 'df' with columns 'Age' and 'Salary'. In order to select all rows where the age is greater than 30 and the salary is less than 50000, which of the following code is correct?

Solution

✅ Correct Option: 2

Boolean filtering in pandas is written as df[condition]. Each condition is wrapped in its own parentheses and joined with & (element-wise AND), so df[(df['Age']>30) & (df['Salary']<50000)] keeps only rows where both conditions hold.

Without parentheses, & and | bind tighter than > and <, so the expression is evaluated in the wrong order and raises an error.


Option 1: it is missing the outer df[...], so it would not select rows, and it also lacks parentheses.

Option 3: | means OR, not AND, and the parentheses are missing.

Option 4: the comparisons are reversed (<30 and >50000), and the parentheses are missing.

In pandas, use &, | and ~ with parentheses, not Python's and, or and not.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question