B. The filter and where conditions contradict each other.
C. select must come before filter or where.
D. The syntax for where is incorrect.
Solution
Step 1: Analyze filter condition
filter(df['age'] > 20) keeps rows where age is greater than 20.
Step 2: Analyze where condition
where('age < 18') keeps rows where age is less than 18.
Step 3: Identify contradiction
Rows cannot satisfy both conditions simultaneously, so the result will be empty or logically inconsistent.
Final Answer:
The filter and where conditions contradict each other. -> Option B
Quick Check:
Contradictory filters = no matching rows [OK]
Hint: Check if filter and where conditions conflict [OK]
Common Mistakes:
Thinking filter and where cannot be chained
Assuming select must come first
Ignoring logical contradictions in conditions
5. You have a Spark DataFrame df with columns city, temperature, and humidity. You want to select only city and temperature columns, but only for rows where temperature is above 30 and humidity is below 50. Which code snippet correctly does this?
hard
A. df.filter((df.temperature > 30) & (df.humidity < 50)).select('city', 'temperature')
B. df.select('city', 'temperature').where('temperature > 30 AND humidity < 50')
C. df.select('city', 'temperature').filter((df.temperature > 30) & (df.humidity < 50))
D. df.select('city', 'temperature').where('temperature > 30').filter('humidity < 50')
Solution
Step 1: Filter rows first based on both conditions
We must first keep rows where temperature > 30 and humidity < 50. This is done by filter or where with both conditions combined.
Step 2: Select only the desired columns after filtering
After filtering, select only city and temperature columns to reduce data.
Step 3: Check each option
A: selects first then filters on temperature and humidity -> error (humidity unavailable). B: selects first then where string with both -> error (humidity unavailable). C: filters first then selects -> correct. D: selects first, where on temperature then filter on humidity -> error.