from pyspark.sql import SparkSession from pyspark.sql.functions import countDistinct,…
- User
from pyspark.sql import SparkSession from pyspark.sql.functions import countDistinct, col
Initialize Spark Session
spark = SparkSession.builder.appName("CountDistinctExample").getOrCreate()
Create synthetic data for an e-commerce scenario
data = [ # (order_id, customer_id, product_category, purchase_amount, store_location) (1, "C001", "Electronics", 1200.0, "Paris"), (2, "C002", "Clothing", 150.0, "Lyon"), (3, "C001", "Electronics", 800.0, "Paris"), (4, "C003", "Books", 50.0, "Marseille"), (5, "C002", "Electronics", 1500.0, "Lyon"), (6, "C004", "Clothing", 200.0, "Paris"), (7, "C001", "Books", 75.0, "Paris"), (8, "C003", "Electronics", 950.0, "Marseille"), (9, "C002", "Books", 45.0, "Lyon"), (10, "C001", "Clothing", 180.0, "Paris") ]
Define schema and create DataFrame
columns = ["order_id", "customer_id", "product_category", "purchase_amount", "store_location"] df = spark.createDataFrame(data, columns)
Show the initial dataset
print("Initial Dataset:") df.show()
Example of using countDistinct to analyze customer behavior by location
analysis = df.groupBy("store_location").agg( countDistinct("customer_id").alias("unique_customers"), countDistinct("product_category").alias("unique_categories") )
print("\nAnalysis of Unique Customers and Categories by Location:") analysis.show()
Calculate the number of unique customers who bought each product category
category_customer_analysis = df.groupBy("product_category").agg( countDistinct("customer_id").alias("unique_customers") )
print("\nNumber of Unique Customers per Product Category:") category_customer_analysis.show()
Stop Spark session
spark.stop()
Q- okii i like the teaching style in programming where given a data Set “small one” Q- here show me step by step manula execution how from the input data Set → step (instrction) in the code are transformation the data → and the final output Q- so can do this style in this given example Q- where you show me a details step by step execution here
- Assistant