How do you one-hot encode a string column with Spark ML?
- Exam domain
- Data Processing20% of the exam
- Difficulty
- Medium
- In this mock
- 10 questions on this domainPractise this domain
Why the exam asks this
Data Processing (20% of the exam)
Objective in the exam guide: Use one-hot encoding for categorical features
One-hot encoding is named.
Why C is the answer
StringIndexer to turn strings into indices, then OneHotEncoder on the indices
OneHotEncoder works on numeric category indices. StringIndexer maps strings to indices first.
Remember: Index, then one-hot.
How it works
Spark ML one-hot encoding needs indexed categories.
In detail
- StringIndexer, then OneHotEncoder.
- Then VectorAssembler.
Every option, checked
Knowing why each wrong option fails is how you rule it out on exam day.
A. VectorAssembler on the string columnWrong
VectorAssembler needs numeric inputs.
B. Imputer with strategy "onehot"Wrong
Imputer has no such strategy.
C. StringIndexer to turn strings into indices, then OneHotEncoder on the indicesRight
Index, then one-hot.
D. OneHotEncoder directly on the string column, which accepts raw text values as inputWrongMost tempting
OneHotEncoder needs indices, not strings.
Why it tempts: The encoder name suggests it handles strings.
Use case
An illustrative scenario, not a real incident.
Illustrative: plan_type becomes plan_idx, then a sparse plan_vec.
See it in different ways
flowchart LR S0["StringIndexer"] --> S1["OneHotEncoder"] --> S2["VectorAssembler"] --> S3["Estimator"]
How to read this chart
- Read it in order: StringIndexer, then OneHotEncoder, then VectorAssembler, then Estimator.
mindmap
root(("Categorical encoding"))
n1["StringIndexer"]
n2["Strings to indices"]
n3["OneHotEncoder"]
n4["Indices to vectors"]How to read this chart
- The centre is "Categorical encoding".
- "StringIndexer" covers "Strings to indices".
- "OneHotEncoder" covers "Indices to vectors".