I have a PySpark DataFrame like this:
| Id | X | Y | Z |
|---|---|---|---|
| 1 | 1 | 1 | one,two,three |
| 2 | 1 | 2 | one,two,four,five |
| 3 | 2 | 1 | four,five |
And I am looking to convert the Z-column into separate columns, where the value of each row should be 1 or 0 based on whether or not that particular row contains the value of the column:
| Id | X | Y | one | two | three | four | five |
|---|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 |
| 2 | 1 | 2 | 1 | 1 | 0 | 1 | 1 |
| 3 | 2 | 1 | 0 | 0 | 0 | 1 | 1 |
Edit: So far I have tried exploding the Z-column containing the list of values I would like to add as columns, but I couldn't find a way to dynamically set the resulting column name to the value of the list items. I also tried collect the dataframe rows to loop over them and manually create a 2d-array with new columns, however this results in Spark/Databricks/the cluster crashing.

