我有以下数据框,其中某些列包含数组。 (我们使用的是Spark 1.6)
+--------------------+--------------+------------------+--------------+--------------------+-------------+
| UserName| col1 | col2 |col3 |col4 |col5 |
+--------------------+--------------+------------------+--------------+--------------------+-------------+
|foo |[Main, Indi...|[1777203, 1777203]| [GBP, GBP]| [CR, CR]| [143, 143]|
+--------------------+--------------+------------------+--------------+--------------------+-------------+
我希望得到以下结果:
+--------------------+--------------+------------------+--------------+--------------------+-------------+
| UserName| explod | explod2 |explod3 |explod4 |explod5 |
+--------------------+--------------+------------------+--------------+--------------------+-------------+
|NNNNNNNNNNNNNNNNN...| Main |1777203 | GBP | CR | 143 |
|NNNNNNNNNNNNNNNNN...|Individual |1777203 | GBP | CR | 143 |
----------------------------------------------------------------------------------------------------------
我尝试了横向视图:
sqlContext.sql("SELECT `UserName`, explod, explod2, explod3, explod4, explod5 FROM sourceDF
LATERAL VIEW explode(`col1`) sourceDF AS explod
LATERAL VIEW explode(`col2`) explod AS explod2
LATERAL VIEW explode(`col3`) explod2 AS explod3
LATERAL VIEW explode(`col4`) explod3 AS explod4
LATERAL VIEW explode(`col5`) explod4 AS explod5")
但是我得到了笛卡尔积,其中有很多重复项。 我已经尝试过相同的方法,但使用列法将所有列都爆炸了,但仍然有很多重复项
.withColumn("col1", explode($"col1"))...
我当然可以对最终数据帧做一个区分,但这不是一个很好的解决方案。 有什么方法可以使列爆炸而又不会得到所有重复项?
谢谢!
答案 0 :(得分:2)
如果您使用的是Spark 2.4.0或更高版本,则arrays_zip
使任务更容易
val df = Seq(
("foo",
Seq("Main", "Individual"),
Seq(1777203, 1777203),
Seq("GBP", "GBP"),
Seq("CR", "CR"),
Seq(143, 143)))
.toDF("UserName", "col1", "col2", "col3", "col4", "col5")
df.select($"UserName",
explode(arrays_zip($"col1", $"col2", $"col3", $"col4", $"col5")))
.select($"UserName", $"col.*")
.show()
输出:
+--------+----------+-------+----+----+----+
|UserName| col1| col2|col3|col4|col5|
+--------+----------+-------+----+----+----+
| foo| Main|1777203| GBP| CR| 143|
| foo|Individual|1777203| GBP| CR| 143|
+--------+----------+-------+----+----+----+