PySpark is the enterprise gold standard for big data science. In this class, we write distributed data transformations, register temporary SQL views, and run analytical queries across multi-terabyte datasets.
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
# Initialize local multi-threaded SparkSession
spark = SparkSession.builder \
.appName("VeewomDataScienceBigData") \
.config("spark.driver.memory", "4g") \
.getOrCreate()
# Create sample distributed DataFrame
data = [
("Alice", "Engineering", 125000, "US"),
("Bob", "Marketing", 85000, "UK"),
("Charlie", "Engineering", 140000, "US"),
("David", "Sales", 92000, "CA"),
("Eva", "Engineering", 160000, "CA"),
("Frank", "Marketing", 91000, "US")
]
columns = ["employee_name", "department", "salary", "country"]
df = spark.createDataFrame(data, columns)
# 1. High-Performance PySpark DataFrame Transformations
df_summary = (
df
.filter(F.col("salary") > 90000)
.groupBy("department")
.agg(
F.count("employee_name").alias("headcount"),
F.round(F.avg("salary"), 2).alias("avg_salary"),
F.max("salary").alias("max_salary")
)
.sort("avg_salary", ascending=False)
)
df_summary.show()
# 2. Native Spark SQL Query Execution
df.createOrReplaceTempView("employees")
sql_result = spark.sql("""
SELECT
country,
department,
COUNT(*) AS total_staff,
ROUND(AVG(salary), 2) AS dept_avg
FROM employees
GROUP BY country, department
ORDER BY country, dept_avg DESC
""")
sql_result.show()
# 3. Distributed Window Functions in PySpark
from pyspark.sql.window import Window
dept_window = Window.partitionBy("department").orderBy(F.col("salary").desc())
df_ranked = df.withColumn("dept_salary_rank", F.dense_rank().over(dept_window))
df_ranked.show()
# 4. High-Speed Broadcast Hash Join
departments_meta = spark.createDataFrame([
("Engineering", "Building 4", "Tech"),
("Marketing", "Building 1", "Growth"),
("Sales", "Building 2", "Revenue")
], ["department", "location", "division"])
# Broadcast small lookup table to avoid expensive cluster shuffle
df_joined = df.join(F.broadcast(departments_meta), on="department", how="inner")
df_joined.show()
When training models on 500 million rows, standard Scikit-Learn will run out of memory. Spark MLlib distributes feature vectorization and gradient calculations across the entire worker cluster:
from pyspark.ml.feature import VectorAssembler, StandardScaler
from pyspark.ml.classification import LogisticRegression
from pyspark.ml import Pipeline
# Assemble features into a single distributed vector column
assembler = VectorAssembler(inputCols=["salary"], outputCol="raw_features")
scaler = StandardScaler(inputCol="raw_features", outputCol="features")
lr = LogisticRegression(featuresCol="features", labelCol="label", maxIter=20)
pipeline = Pipeline(stages=[assembler, scaler, lr])
# model = pipeline.fit(training_df)
When writing out large datasets with PySpark, always partition by low-cardinality temporal or geographical columns: df.write.partitionBy("year", "month").parquet("s3://my-lake/orders/"). This ensures downstream queries perform fast partition pruning.
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Learn the cluster manager, driver node, and executor architecture.
Translate single-node Pandas code into scalable PySpark DataFrames.
Connect PySpark to cloud data lakehouses for distributed analytics.
Package PySpark batch transformation scripts inside Docker containers.