We have a pyspark dataframe with several columns containing arrays with multiple values. Our goal is to have each of this values of these columns in several rows, keeping the initial different columns. So, starting with something like this:
data = [
("A", ["a", "c"], ["1", "5"]),
("B", ["a", "b"], None),
("C", [], ["1"]),
]
Whats:
+---+------+------+
|id |list_a|list_b|
+---+------+------+
|A |[a, c]|[1, 5]|
|B |[a, b]|null |
|C |[] |[1] |
+---+------+------+
We would like to end up having:
+---+----+----+
|id |col |col |
+---+----+----+
|A |a |null|
|A |c |null|
|A |null|1 |
|A |null|5 |
|B |a |null|
|B |b |null|
|C |null|1 |
+---+----+----+
We are thinking about several approaches:
- prefixing each value with a column indicator, merge all the arrays into a single one, explode it and reorganize the different values into different columns
- split the dataframe into several, each one with one of these array columns, explode the array column and then, concatenating the dataframes
But all of them smell like dirty, complex, error prone and inefficient workarounds.
Does anyone have an idea about how to solve this in an elegant manner?