如何将多列对分解为多行?
我有一个包含以下内容的数据框
client, type, address, type_2, address_2
abc, home, 123 Street, business, 456 Street
我想要一个带有以下内容的最终数据框
client, type, address
abc, home, 123 Street
abc, business, 456 Street
我尝试使用下面的代码,但它返回 4 条记录而不是我想要的两条记录
df
.withColumn("type", explode(array("type", "type_2")))
.withColumn("address", explode(array("address", "address_2")))
我可以用两个单独的数据帧来做到这一点并执行联合,但我想看看是否有另一种方法可以在单个数据帧中做到这一点
谢谢
最佳答案
你可以使用结构来做到这一点:
df
.withColumn("str",explode(
array(
struct($"type",$"address"),
struct($"type_2".as("type"),$"address_2".as("address"))))
)
.select($"client",$"str.*")
.show()
给
+------+--------+----------+
|client| type| address|
+------+--------+----------+
| abc| home|123 Street|
| abc|business|456 Street|
+------+--------+----------+
关于Scala Spark 将多列对分解为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867060/