我有一个数据框myDf
其中包含点对数组(即 x 和 y 坐标),它具有以下模式:
myDf.printSchema
root
|-- pts: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- x: float (nullable = true)
| | |-- y: float (nullable = true)
我想要得到x
and y
作为单独的普通 ScalaArray
的。我想我需要应用爆炸功能,但我不知道如何应用。我尝试申请this https://stackoverflow.com/questions/37172254/select-specific-columns-in-spark-dataframes-from-array-of-struct解决方案,但我无法让它工作。
我正在使用 Spark 1.6.1 和 Scala 2.10
编辑:我意识到我误解了 Spark 的工作原理,只有收集数据(或使用 UDF)才能获取实际的数组
假设myDf
is DataFrame
读自json
file:
{
"pts":[
{
"x":0.0,
"y":0.1
},
{
"x":1.0,
"y":1.1
},
{
"x":2.0,
"y":2.1
}
]
}
你可以做explode
像这样:
Java:
DataFrame pts = myDf.select(org.apache.spark.sql.functions.explode(df.col("pts")).as("pts"))
.select("pts.x", "pts.y");
pts.printSchema();
pts.show();
Scala:
// Sorry I don't know Scala
// I just interpreted from the above Java code
// Code here may have some mistakes
val pts = myDf.select(explode($"pts").as("pts"))
.select($"pts.x", $"pts.y")
pts.printSchema()
pts.show()
这是打印的架构:
root
|-- x: double (nullable = true)
|-- y: double (nullable = true)
这是pts.show()
result:
+---+---+
| x| y|
+---+---+
|0.0|0.1|
|1.0|1.1|
|2.0|2.1|
+---+---+
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)