Home › Interview Questions › Create PySpark DataFrames from the given data, rem…

Create PySpark DataFrames from the given data, remove duplicate orders using 'order_id', keep only orders with status 'Completed', calculate each customer's total completed order amount and number of completed orders, and join the result with the customers DataFrame to get customer names.

🟡 Medium Coding Mid level
1Times asked
Nov 2026Last seen
Nov 2026First seen

💡 Model Answer

Here’s a concise PySpark solution that follows the steps you described. First, create two DataFrames from your source data. Then drop duplicate orders by order_id, filter for status = 'Completed', aggregate the amount and count per customer_id, and finally join the result with the customers DataFrame to bring in the customer name. The code below assumes you already have two Python lists or Pandas DataFrames named orders_data and customers_data.

orders_df = spark.createDataFrame(orders_data, ['order_id','customer_id','amount','status'])

customers_df = spark.createDataFrame(customers_data, ['customer_id','name','city'])

cleaned_orders = (orders_df

.dropDuplicates(['order_id'])
.filter(col('status') == 'Completed'))

agg_df = (cleaned_orders

.groupBy('customer_id')
.agg(
    sum('amount').alias('total_amount'),
    count('order_id').alias('completed_orders')
))

result_df = agg_df.join(customers_df, on='customer_id', how='inner')

result_df.select('customer_id', 'name', 'total_amount', 'completed_orders').show()

Each transformation is a single pass over the data, so the overall cost is O(n) for the filter, dropDuplicates, and aggregation, and O(n log n) for the join depending on the catalyst optimizer. The code is fully reproducible in a PySpark shell or notebook.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500