Spark & PySpark
Feature Engineering in Spark: From Raw Data to ML-Ready
💡 Before any model shines, your data must speak the same language.
In machine learning, 80% of success lies in data preparation — not in choosing the “best” algorithm.
Feature engineering is the process of transforming raw, messy, or mixed-type data into clean, structured, and machine-learning-ready features.
When working with large-scale data pipelines, Spark MLlib is a powerhouse for feature engineering — scalable, distributed, and seamlessly integrated with model training.
In this blog, we’ll go step-by-step through how Spark makes feature engineering simple, modular, and production-ready.
🧩 1. Why Feature Engineering Matters
Raw data is full of imperfections — missing values, categorical text, inconsistent scales, or skewed distributions.
Models trained directly on such data perform poorly or even fail to converge.
Feature engineering bridges the gap between raw inputs and usable features.
Think of it as:
Data → Transformation → Features → Model → Prediction
Goal: Convert real-world data (CSV, Parquet, logs, etc.) into consistent numeric feature vectors.
💡 Good feature engineering improves model accuracy more than switching algorithms.
⚙️ 2. Spark’s Feature Engineering Toolbox
Spark MLlib provides a rich set of Transformers and Estimators that can be combined into end-to-end feature pipelines.
Here’s a quick reference table 👇

Each transformer plays a specific role in preparing raw data for modeling — from cleaning and encoding to scaling and dimensionality reduction. These building blocks form the backbone of scalable ML pipelines in Spark.
💡 All of these can be chained inside a Spark ML pipeline.
🧪 3. Example: From Raw Data to Feature Vector
Let’s walk through a simple example of turning raw demographic data into ML-ready vectors.
from pyspark.sql import SparkSession
from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler, StandardScaler
from pyspark.ml import Pipeline
spark = SparkSession.builder.appName("FeatureEngineering").getOrCreate()
# 🧾 Step 1: Sample data
data = [
(0, "male", 25, 40000),
(1, "female", 35, 60000),
(2, "female", 45, 80000)
]
columns = ["id", "gender", "age", "income"]
df = spark.createDataFrame(data, columns)
Explanation:
We start with a small dataset that mimics a demographic input — gender (categorical), age, and income (numeric).
These must be converted into numerical form before model training.
🏗️ Step 2: Build a Transformation Pipeline
# Index categorical feature
indexer = StringIndexer(inputCol="gender", outputCol="gender_indexed")
# One-hot encode gender
encoder = OneHotEncoder(inputCols=["gender_indexed"], outputCols=["gender_vec"])
# Combine features
assembler = VectorAssembler(
inputCols=["gender_vec", "age", "income"], outputCol="features"
)
# Scale features for model stability
scaler = StandardScaler(inputCol="features", outputCol="scaled_features")
# Create ML pipeline
pipeline = Pipeline(stages=[indexer, encoder, assembler, scaler])
model = pipeline.fit(df)
transformed = model.transform(df)
transformed.select("features", "scaled_features").show(truncate=False)
Flow Explanation:
StringIndexer→ converts gender text labels to numeric codes.OneHotEncoder→ turns those numeric codes into binary vectors (0/1).VectorAssembler→ merges all columns into a single vector for the model.StandardScaler→ normalizes the combined vector to handle different value scales.
✅ Output:
A compact, scaled feature vector per record — ready for machine learning.
🔍 4. Handling Missing and Skewed Data
Real-world data often contains missing values or skewed distributions.
Spark handles both elegantly.
🧱 Handling Missing Values
from pyspark.ml.feature import Imputer
imputer = Imputer(
inputCols=["age", "income"],
outputCols=["age_imputed", "income_imputed"]
)
df_imputed = imputer.fit(df).transform(df)
👉 Replaces nulls with mean or median automatically — essential before training models.
⚖️ Handling Skewed Features
If features are heavily skewed (like income or transaction values), you can apply log transformations:
from pyspark.sql.functions import log1p
df = df.withColumn("log_income", log1p(df["income"]))
log1p() to handle skewed income distribution.This helps normalize long-tail distributions — improving model performance and convergence.
If your data has long tails (e.g., income, transactions), applying a log transformation stabilizes variance and improves model convergence.
💡 Rule of thumb: Normalize or log-transform features that vary across magnitudes.
🧠 5. Text Feature Engineering in Spark
Text data requires special handling. Spark provides built-in transformers for NLP-style preprocessing.
from pyspark.ml.feature import Tokenizer, HashingTF, IDF
from pyspark.ml import Pipeline
text_df = spark.createDataFrame([
(0, "Spark makes big data simple"),
(1, "Feature engineering at scale")
], ["id", "text"])
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol="words", outputCol="raw_features", numFeatures=20)
idf = IDF(inputCol="raw_features", outputCol="tfidf_features")
pipeline = Pipeline(stages=[tokenizer, hashingTF, idf])
model = pipeline.fit(text_df)
result = model.transform(text_df)
result.select("tfidf_features").show(truncate=False)
Explanation:
Tokenizer→ splits sentences into wordsHashingTF→ converts words to frequency vectorsIDF→ scales them based on their importance (TF-IDF)
💡 TF-IDF is powerful for document classification, clustering, or sentiment analysis in Spark.
📦 6. Feature Selection & Dimensionality Reduction
When you have hundreds of features, reducing dimensionality speeds up training and avoids overfitting.
from pyspark.ml.feature import PCA
pca = PCA(k=3, inputCol="scaled_features", outputCol="pca_features")
pca_model = pca.fit(transformed)
pca_result = pca_model.transform(transformed)
pca_result.select("pca_features").show(truncate=False)
Explanation:
PCA compresses high-dimensional vectors into a few principal components — preserving variance while cutting redundancy.
💡 Use PCA when you have >50 features or face multicollinearity
🧩 7. End-to-End Feature Engineering Workflow

Each block represents a modular MLlib transformer or estimator that can be reused, replaced, or tuned independently.
This modularity allows you to build robust, scalable feature pipelines.
💡 Tip: Save your final pipeline model using .write().overwrite().save(path) for reuse in production.
🌍 8. Real-World Use Cases
Feature engineering is the “invisible hero” behind successful ML pipelines.
Here’s how enterprises use Spark MLlib feature engineering at scale:

These workflows prove that good features outperform fancy models — especially when data scales to billions of rows.
🔗 9. Run This Notebook on Google Colab
You can try all examples directly in Google Colab ⬇️
👉 Open Feature Engineering with Spark on Colab
🎯 10. Conclusion
Feature Engineering is where data meets intelligence.
With Spark MLlib, you can build end-to-end, distributed, and reproducible feature pipelines — from raw logs to ready-to-train datasets.
Key Takeaways:
✅ Transform raw data into machine-readable numeric vectors
✅ Handle missing, categorical, and skewed data efficiently
✅ Scale across clusters effortlessly
✅ Integrate seamlessly with MLlib model training pipelines
💬 In Spark, feature engineering isn’t a preprocessing step — it’s the foundation of scalable machine learning.
⚡ Next in Series:
“Building a Simple Classifier with Spark MLlib” — where we’ll use these engineered features to train and evaluate a real model.
💬 Final Words
If this guide helped you understand Spark MLlib, you’re already thinking like a distributed data scientist.
Follow TheDataForge for more deep dives into PySpark, MLlib, and data engineering workflows — because big data deserves simple explanations. ⚡