Scala Spark 将多列对分解为行

标签 scala apache-spark

如何将多列对分解为多行?

我有一个包含以下内容的数据框

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/

相关文章:

scala - Cassandra spark 连接器 joinWithCassandraTable 在具有不同名称的字段上

python - 用于比较稀疏向量的 Pyspark UDF

scala - 为什么 from_json 失败并显示 "not found : value from_json"?

scala - akka 集群连接被拒绝 : address is now > gated for [5000] ms

scala - 方法依赖性和错误处理

apache-spark - Spark 2.0 : 4 Rows. IllegalArgumentException:绑定(bind)必须为正

apache-spark - Spark的takeSample()结果分两个阶段

scala - 如何将 Scala 源附加到我的 Maven jar?

scala - HBase - Scala - 无法初始化类 ProtobufUtil

scala - 带有只读基目录的 SBT