将包含数组列的数据框转换为长数据帧

时间:2018-02-05 19:19:55

标签: apache-spark pyspark apache-spark-sql spark-dataframe

我的列是spark DataFrame中的数组。我想将数据帧转换为长数据帧,其中数组的每个元素都在一个新行中。 我希望它像下面那样。

例如

spark.createDataFrame([(['abcd','cdf','dfg'],['123']),(['a'],['45','67',98'])],['s','d']).show()

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用explode

df = spark.createDataFrame([(['abcd','cdf','dfg'],['123']),(['a'],['45','67','98'])],['s','d'])

df.createOrReplaceTempView("tbl")

spark.sql("select x, y from tbl lateral view explode(s) v1 as x lateral view explode(d) v2 as y").show()

+----+---+
|   x|  y|
+----+---+
|abcd|123|
| cdf|123|
| dfg|123|
|   a| 45|
|   a| 67|
|   a| 98|
+----+---+