📖 Scenario: You work as a data analyst for a small online bookstore. You have a dataset of books with details like title, author, genre, and price. Your manager wants you to find books that are affordable and belong to a specific genre.
🎯 Goal: Build a Spark DataFrame with book data, set a price limit, filter books by genre and price using select, filter, and where operations, and display the filtered results.
📋 What You'll Learn
Create a Spark DataFrame with exact book data
Create a variable for the maximum price allowed
Use select to choose specific columns
Use filter or where to select books by genre and price
Print the final filtered DataFrame
💡 Why This Matters
🌍 Real World
Filtering and selecting data is a common task in data analysis to focus on relevant information, such as affordable books in a specific genre.
💼 Career
Data analysts and data scientists often use select, filter, and where operations in Spark to prepare and explore large datasets efficiently.
Progress0 / 4 steps
1
Create the books DataFrame
Create a Spark DataFrame called books_df with these exact entries: {'title': 'The Alchemist', 'author': 'Paulo Coelho', 'genre': 'Fiction', 'price': 10}, {'title': 'Deep Learning', 'author': 'Ian Goodfellow', 'genre': 'Education', 'price': 50}, {'title': 'Clean Code', 'author': 'Robert C. Martin', 'genre': 'Education', 'price': 40}, {'title': 'The Hobbit', 'author': 'J.R.R. Tolkien', 'genre': 'Fiction', 'price': 15}, {'title': 'Cooking 101', 'author': 'Jamie Oliver', 'genre': 'Cooking', 'price': 20}. Use Spark's createDataFrame method with a list of dictionaries.
Apache Spark
Hint
Use spark.createDataFrame with a list of dictionaries containing the exact book details.
2
Set the maximum price limit
Create a variable called max_price and set it to 20 to represent the maximum price allowed for books.
Apache Spark
Hint
Just create a variable named max_price and assign it the value 20.
3
Filter books by genre and price
Use select to choose the columns 'title', 'author', and 'price' from books_df. Then use filter or where to keep only books where genre is 'Fiction' and price is less than or equal to max_price. Save the result in a new DataFrame called filtered_books.
Apache Spark
Hint
Use select('title', 'author', 'price') and then where with conditions joined by &.
4
Display the filtered books
Use print and filtered_books.show() to display the filtered books DataFrame.
Apache Spark
Hint
Use print('Filtered books:') and then filtered_books.show() to display the data.
Practice
(1/5)
1. What does the select operation do in Apache Spark DataFrame?
easy
A. It chooses specific columns from the DataFrame.
B. It filters rows based on a condition.
C. It sorts the DataFrame by a column.
D. It adds new columns to the DataFrame.
Solution
Step 1: Understand the purpose of select
The select operation is used to pick specific columns from a DataFrame, reducing the data to only those columns.
Step 2: Differentiate from filtering rows
Filtering rows is done by filter or where, not by select.
Final Answer:
It chooses specific columns from the DataFrame. -> Option A
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.