1

I have a Spark dataframe that has two arrays like below:

df = spark.createDataFrame(
  [((["Person", "Company", "Person", "Person"], 
     ["John", "Company1", "Jenny", "Jessica"]))], 
  ["Type", "Value"])
df.show()

+--------------------+--------------------+
|                Type|               Value|
+--------------------+--------------------+
|[Person, Company,...|[John, Company1, ...|
+--------------------+--------------------+

I want to transform it to a tidy version that looks like this:

df = spark.createDataFrame(
    [
        ("Person", "John"), 
        ("Company", "Company1"), 
        ("Person", "Jenny"), 
        ("Person", "Jessica"),
    ],
    ["Type", "Value"])
df.show()

+-------+--------+
|   Type|   Value|
+-------+--------+
| Person|    John|
|Company|Company1|
| Person|   Jenny|
| Person| Jessica|
+-------+--------+

PySpark or SparkSQL solutions appreciated. TIA.

notNull
  • 30,258
  • 4
  • 35
  • 50
Frank B.
  • 1,813
  • 5
  • 24
  • 44

1 Answers1

2

From Spark-2.4.0 Use arrays_zip function to zip two arrays(lists) then do explode.

For Spark < 2.4 use udf to create zip.

Example:

df = spark.createDataFrame(
  [((["Person", "Company", "Person", "Person"], 
     ["John", "Company1", "Jenny", "Jessica"]))], 
  ["Type", "Value"])

from pyspark.sql.functions import *
df.withColumn("az",explode(arrays_zip(col("Type"),col("Value")))).select("az.*").show()
#+-------+--------+
#|   Type|   Value|
#+-------+--------+
#| Person|    John|
#|Company|Company1|
#| Person|   Jenny|
#| Person| Jessica|
#+-------+--------+

#using spark sql
df.createOrReplaceTempView("tmp")
sql("select col.* from (select explode(arrays_zip(Type,Value)) from tmp)q").show()
#+-------+--------+
#|   Type|   Value|
#+-------+--------+
#| Person|    John|
#|Company|Company1|
#| Person|   Jenny|
#| Person| Jessica|
#+-------+--------+
notNull
  • 30,258
  • 4
  • 35
  • 50