PySpark practice problems on a real dataset (NYC taxi)

Eight PySpark practice problems on 3 million NYC taxi trips: cleaning, joins, window functions, Spark SQL, partitioned writes, with real results.

5 min read8 stepsReal lab output

By Verth Labs · Published

These are eight PySpark practice problems on one real dataset: a month of New York City yellow taxi trips, about 3 million rows. Each problem is a pattern you will meet at work or in an interview (cleaning, aggregation, joins, window functions, SQL, partitioned writes and reading a query plan). Under each one is the code we ran and the output we got on a Big Data Labs cluster on 14 November 2026: PySpark on YARN, reading the data from HDFS.

Try each problem yourself before you read the solution. The numbers below let you check your answer.

The setup

The dataset is the NYC Taxi & Limousine Commission trip records for January 2024, already in HDFS in Big Data Labs as Parquet (dataset details). Open a Pyspark 3.5 notebook and start a session:

from pyspark.sql import SparkSession, functions as F, Window

spark = SparkSession.builder.appName("nyc-taxi-practice").getOrCreate()
print(spark.version, spark.sparkContext.master)
Output
3.5.9 yarn

yarn as the master means your executors run on the cluster's worker nodes, not inside your notebook. That matters for problem 8.

trips = spark.read.parquet("/public/datasets/nyc-taxi/parquet/small/trips")
zones = spark.read.parquet("/public/datasets/nyc-taxi/parquet/small/zones")
print(trips.count(), zones.count())
trips.printSchema()
Output
2964624 265
root
 |-- VendorID: integer (nullable = true)
 |-- tpep_pickup_datetime: timestamp_ntz (nullable = true)
 |-- tpep_dropoff_datetime: timestamp_ntz (nullable = true)
 |-- passenger_count: integer (nullable = true)
 |-- trip_distance: double (nullable = true)
 |-- RatecodeID: integer (nullable = true)
 |-- store_and_fwd_flag: string (nullable = true)
 |-- PULocationID: integer (nullable = true)
…
Show full output (24 lines)
2964624 265
root
 |-- VendorID: integer (nullable = true)
 |-- tpep_pickup_datetime: timestamp_ntz (nullable = true)
 |-- tpep_dropoff_datetime: timestamp_ntz (nullable = true)
 |-- passenger_count: integer (nullable = true)
 |-- trip_distance: double (nullable = true)
 |-- RatecodeID: integer (nullable = true)
 |-- store_and_fwd_flag: string (nullable = true)
 |-- PULocationID: integer (nullable = true)
 |-- DOLocationID: integer (nullable = true)
 |-- payment_type: integer (nullable = true)
 |-- fare_amount: double (nullable = true)
 |-- extra: double (nullable = true)
 |-- mta_tax: double (nullable = true)
 |-- tip_amount: double (nullable = true)
 |-- tolls_amount: double (nullable = true)
 |-- improvement_surcharge: double (nullable = true)
 |-- total_amount: double (nullable = true)
 |-- congestion_surcharge: double (nullable = true)
 |-- airport_fee: double (nullable = true)
 |-- cbd_congestion_fee: double (nullable = true)
 |-- year: integer (nullable = true)
 |-- month: integer (nullable = true)

2,964,624 trips and 265 taxi zones. Note timestamp_ntz: the times have no time zone, which is how the source files store them.

Step 1: Problem 1: the busiest days

Task. Count trips per pickup date and show the five busiest days.

daily = (trips.withColumn("pickup_date", F.to_date("tpep_pickup_datetime"))
              .groupBy("pickup_date").count()
              .orderBy(F.desc("count")))
daily.show(5)
Output
+-----------+------+
|pickup_date| count|
+-----------+------+
| 2024-01-27|110515|
| 2024-01-17|110365|
| 2024-01-18|110358|
| 2024-01-25|110318|
| 2024-01-20|108768|
+-----------+------+
only showing top 5 rows

Step 2: Problem 2: find and remove bad rows

Task. Real data is messy. Count the rows with a fare or distance of zero or less, or a pickup time outside 2024, then keep only clean January 2024 rows.

bad = trips.filter((F.col("fare_amount") <= 0) | (F.col("trip_distance") <= 0)
                   | (F.year("tpep_pickup_datetime") != 2024))
print("suspect rows:", bad.count())

clean = trips.filter((F.col("fare_amount") > 0) & (F.col("trip_distance") > 0)
                     & (F.year("tpep_pickup_datetime") == 2024)
                     & (F.month("tpep_pickup_datetime") == 1))
print("clean rows:", clean.count())
Output
suspect rows: 94924
clean rows: 2869697

About 3.2% of the rows are suspect: refunds and voids show up as negative fares, some trips have zero distance, and a few have clocks set to the wrong year. Always check before you aggregate.

Step 3: Problem 3: tip percentage by hour

Task. For card payments (payment_type = 1), compute the average tip as a percentage of the fare for each hour of the day.

(clean.filter(F.col("payment_type") == 1)
      .withColumn("hour", F.hour("tpep_pickup_datetime"))
      .groupBy("hour")
      .agg(F.round(F.avg(F.col("tip_amount") / F.col("fare_amount")) * 100, 1).alias("avg_tip_pct"),
           F.count("*").alias("trips"))
      .orderBy("hour")
      .show(24))
Output
+----+-----------+------+
|hour|avg_tip_pct| trips|
+----+-----------+------+
|   0|       25.2| 58815|
|   1|       25.3| 39145|
|   2|       25.5| 27432|
|   3|       49.0| 17070|
|   4|       24.8|  9908|
|   5|       22.7| 12175|
|   6|       22.4| 28990|
…
Show full output (28 lines)
+----+-----------+------+
|hour|avg_tip_pct| trips|
+----+-----------+------+
|   0|       25.2| 58815|
|   1|       25.3| 39145|
|   2|       25.5| 27432|
|   3|       49.0| 17070|
|   4|       24.8|  9908|
|   5|       22.7| 12175|
|   6|       22.4| 28990|
|   7|       23.6| 63628|
|   8|       39.3| 91102|
|   9|       24.3|100997|
|  10|       24.7|106898|
|  11|       24.7|115591|
|  12|       24.7|125452|
|  13|       24.7|129990|
|  14|       24.6|140849|
|  15|       24.5|146181|
|  16|       26.6|149329|
|  17|       26.9|163657|
|  18|       27.3|169185|
|  19|       27.2|147919|
|  20|       26.3|129237|
|  21|       26.1|128835|
|  22|       25.7|112937|
|  23|       25.4| 83058|
+----+-----------+------+

The catch. Hours 3 and 8 jump to 49% and 39%. That is not generous early-morning riders: a handful of trips with a tiny fare (a few cents) and a normal tip produce enormous percentages, and an average is pulled up by them. Try F.percentile_approx(..., 0.5) for the median, or filter out fares under $3, and compare. Spotting outliers like this is the real skill being practiced.

Step 4: Problem 4: busiest pickup zones (a join)

Task. Join trips to the zone lookup table to get borough and zone names, then rank pickup zones by number of trips and show the average total paid.

pu = zones.select(F.col("LocationID").alias("PULocationID"),
                  F.col("Borough").alias("pu_borough"),
                  F.col("Zone").alias("pu_zone"))
top = (clean.join(F.broadcast(pu), "PULocationID")
            .groupBy("pu_borough", "pu_zone")
            .agg(F.count("*").alias("trips"), F.round(F.avg("total_amount"), 2).alias("avg_total"))
            .orderBy(F.desc("trips")))
top.show(10, truncate=False)
Output
+----------+----------------------------+------+---------+
|pu_borough|pu_zone                     |trips |avg_total|
+----------+----------------------------+------+---------+
|Manhattan |Midtown Center              |140140|23.96    |
|Manhattan |Upper East Side South       |140120|19.78    |
|Queens    |JFK Airport                 |138450|80.88    |
|Manhattan |Upper East Side North       |133961|20.26    |
|Manhattan |Midtown East                |104345|23.33    |
|Manhattan |Times Sq/Theatre District   |102958|26.87    |
|Manhattan |Penn Station/Madison Sq West|102152|24.11    |
…
Show full output (15 lines)
+----------+----------------------------+------+---------+
|pu_borough|pu_zone                     |trips |avg_total|
+----------+----------------------------+------+---------+
|Manhattan |Midtown Center              |140140|23.96    |
|Manhattan |Upper East Side South       |140120|19.78    |
|Queens    |JFK Airport                 |138450|80.88    |
|Manhattan |Upper East Side North       |133961|20.26    |
|Manhattan |Midtown East                |104345|23.33    |
|Manhattan |Times Sq/Theatre District   |102958|26.87    |
|Manhattan |Penn Station/Madison Sq West|102152|24.11    |
|Manhattan |Lincoln Square East         |101794|21.33    |
|Queens    |LaGuardia Airport           |87694 |66.38    |
|Manhattan |Upper West Side South       |86468 |21.22    |
+----------+----------------------------+------+---------+
only showing top 10 rows

F.broadcast(pu) tells Spark to send the small zone table (265 rows) to every executor instead of shuffling the 2.9 million trips. Airport trips are fewer than Midtown's but pay three to four times more.

Step 5: Problem 5: top two zones per borough (a window function)

Task. For each borough, keep its two busiest pickup zones.

w = Window.partitionBy("pu_borough").orderBy(F.desc("trips"))
(top.withColumn("rank", F.row_number().over(w))
    .filter("rank <= 2")
    .orderBy("pu_borough", "rank")
    .show(truncate=False))
Output
+-------------+---------------------------+------+---------+----+
|pu_borough   |pu_zone                    |trips |avg_total|rank|
+-------------+---------------------------+------+---------+----+
|Bronx        |Mott Haven/Port Morris     |438   |34.2     |1   |
|Bronx        |Co-Op City                 |362   |44.04    |2   |
|Brooklyn     |Downtown Brooklyn/MetroTech|1294  |33.17    |1   |
|Brooklyn     |Brooklyn Heights           |1169  |33.35    |2   |
|EWR          |Newark Airport             |49    |99.18    |1   |
|Manhattan    |Midtown Center             |140140|23.96    |1   |
|Manhattan    |Upper East Side South      |140120|19.78    |2   |
…
Show full output (17 lines)
+-------------+---------------------------+------+---------+----+
|pu_borough   |pu_zone                    |trips |avg_total|rank|
+-------------+---------------------------+------+---------+----+
|Bronx        |Mott Haven/Port Morris     |438   |34.2     |1   |
|Bronx        |Co-Op City                 |362   |44.04    |2   |
|Brooklyn     |Downtown Brooklyn/MetroTech|1294  |33.17    |1   |
|Brooklyn     |Brooklyn Heights           |1169  |33.35    |2   |
|EWR          |Newark Airport             |49    |99.18    |1   |
|Manhattan    |Midtown Center             |140140|23.96    |1   |
|Manhattan    |Upper East Side South      |140120|19.78    |2   |
|N/A          |Outside of NYC             |741   |79.73    |1   |
|Queens       |JFK Airport                |138450|80.88    |1   |
|Queens       |LaGuardia Airport          |87694 |66.38    |2   |
|Staten Island|Arrochar/Fort Wadsworth    |19    |38.39    |1   |
|Staten Island|Heartland Village/Todt Hill|4     |125.89   |2   |
|Unknown      |N/A                        |9638  |27.36    |1   |
+-------------+---------------------------+------+---------+----+

row_number() gives exactly two rows per borough even when trips tie; use rank() if ties should share a place. Yellow taxis are mostly a Manhattan and airport business, which shows in how small the outer-borough counts are.

Step 6: Problem 6: the same question in Spark SQL

Task. Register the clean DataFrame as a view and answer in SQL: trips and average distance by payment type.

clean.createOrReplaceTempView("trips_clean")
spark.sql("""
SELECT payment_type, COUNT(*) AS trips, ROUND(AVG(trip_distance), 2) AS avg_miles
FROM trips_clean GROUP BY payment_type ORDER BY trips DESC
""").show()
Output
+------------+-------+---------+
|payment_type|  trips|avg_miles|
+------------+-------+---------+
|           1|2298380|     3.29|
|           2| 422747|     3.32|
|           0| 115249|    14.15|
|           4|  22759|     3.42|
|           3|  10562|     2.85|
+------------+-------+---------+

Payment type 1 is credit card and 2 is cash in the TLC data dictionary. Look up what type 0 means in the current dictionary: its average distance of 14 miles makes it another data-quality question worth investigating.

Step 7: Problem 7: write a partitioned table

Task. Write the clean data as Parquet, partitioned by pickup date, into your HDFS home.

(clean.withColumn("pickup_date", F.to_date("tpep_pickup_datetime"))
      .repartition("pickup_date")
      .write.mode("overwrite").partitionBy("pickup_date")
      .parquet("practice/taxi_clean"))
Output
$ hdfs dfs -ls practice/taxi_clean | head -6
Found 32 items
-rw-r--r--   1 vl0000 vl0000          0 2026-11-14 14:45 practice/taxi_clean/_SUCCESS
drwxr-xr-x   - vl0000 vl0000          0 2026-11-14 14:45 practice/taxi_clean/pickup_date=2024-01-01
drwxr-xr-x   - vl0000 vl0000          0 2026-11-14 14:45 practice/taxi_clean/pickup_date=2024-01-02
drwxr-xr-x   - vl0000 vl0000          0 2026-11-14 14:45 practice/taxi_clean/pickup_date=2024-01-03
drwxr-xr-x   - vl0000 vl0000          0 2026-11-14 14:45 practice/taxi_clean/pickup_date=2024-01-04
$ hdfs dfs -du -s -h practice/taxi_clean
56.3 M  56.3 M  practice/taxi_clean

31 date folders plus the _SUCCESS marker. repartition("pickup_date") before the write puts each day's rows in one task, so each folder gets one file instead of one file per task.

Step 8: Problem 8: read the query plan

Task. Read one day back and check that Spark only scans that day's folder.

spark.read.parquet("practice/taxi_clean").filter("pickup_date = '2024-01-15'").explain()

The output, shortened (the column list and paths are cut):

Output
== Physical Plan ==
*(1) ColumnarToRow
+- FileScan parquet [VendorID#489,...,pickup_date#511] Batched: true, DataFilters: [],
   Format: Parquet, Location: InMemoryFileIndex(1 paths)[hdfs://.../user/vl0000/pract...,
   PartitionFilters: [isnotnull(pickup_date#511), (pickup_date#511 = 2024-01-15)],
   PushedFilters: [], ...

PartitionFilters is the line to look for: the filter on the partition column is applied to folder names before any file is opened (partition pruning). A filter on an ordinary column would appear under PushedFilters instead. Open the Spark UI from the lab while a query runs to see the stages and tasks this plan turns into.

Where to go next

  • Run the same notebook on Spark 2.4 and 3.1 in the same lab and compare the plans.
  • Switch to the full slice (parquet/full, three years and about 119 million trips) and watch how the job and the Spark UI change.
  • Stream the same trips into Kafka with the replay tool in the dataset page and redo problem 1 with Structured Streaming.

New to the cluster itself? Start with HDFS commands for practice.