filter and where do the same thing: pick rows by condition.
Examples
Selects only the 'name' and 'age' columns from the data.
Apache Spark
df.select("name", "age")
Filters rows where the 'age' column is greater than 25.
Apache Spark
df.filter(df["age"] > 25)
Filters rows where the 'salary' column is more than 50000 using a string condition.
Apache Spark
df.where("salary > 50000")
Sample Program
This program creates a small table of people with their age and salary. It then shows how to pick columns and filter rows using select, filter, and where.
Apache Spark
from pyspark.sql import SparkSession
# Start Spark session
spark = SparkSession.builder.appName("SelectFilterWhereExample").getOrCreate()
# Create sample data
data = [
("Alice", 30, 60000),
("Bob", 22, 40000),
("Charlie", 35, 70000),
("David", 28, 45000)
]
# Define columns
columns = ["name", "age", "salary"]
# Create DataFrame
df = spark.createDataFrame(data, columns)
# Select name and salary columns
selected_df = df.select("name", "salary")
# Filter rows where age is greater than 25
filtered_df = df.filter(df["age"] > 25)
# Use where to filter rows where salary is greater than 50000
where_df = df.where("salary > 50000")
# Show resultsprint("Selected columns (name, salary):")
selected_df.show()
print("Filtered rows (age > 25):")
filtered_df.show()
print("Where rows (salary > 50000):")
where_df.show()
# Stop Spark session
spark.stop()
OutputSuccess
Important Notes
filter and where do the same job; use whichever you find easier.
select only changes columns, it does not filter rows.
Conditions in filter can be written using column expressions or SQL strings in where.
Summary
Select picks columns you want to keep.
Filter and where pick rows that match a condition.
Use these to focus your data for easier analysis.
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.