如何访问数据框列中的数组元素(标量)

时间:2018-08-31 16:32:17

标签: arrays scala apache-spark dataframe

dfElements2中的第一列是array。我需要在选择纬度和经度的同时选择第一个元素(30002| 30005 | 30158 ...)而不是数组,而不是整个数组:

数据框应如下:

+-----------------------------------+
| short_name  |   lat    |   lng
+-----------------------------------+
|   30002     |37.9796566|-1.1317041|
|   30005     |37.9868856|-1.1371011|
|   30158     | 37.941845|-1.0681918|
|   30006     |37.9971704|-1.0993366|
+-----------------------------------+

您能否告诉我是否有可能编辑命令results.address_components.short_name来访问数组元素?

var DFResults2=DF_Google1.select(explode(DF_Google1 ("results"))).toDF("results")
var dfElements2=DFResults2.select("results.address_components.short_name","results.geometry.location.lat","results.geometry.location.lng")**
var dfElements3=dfElements2.select(explode(dfElements2("short_name"))).toDF("CP")

dfElements2.show()
dfElements2.printSchema()


+--------------------+----------+----------+
|          short_name|       lat|       lng|
+--------------------+----------+----------+
|[30002, Murcia, M...|37.9796566|-1.1317041|
|[30005, Murcia, M...|37.9868856|-1.1371011|
|[30158, Murcia, M...| 37.941845|-1.0681918|
|[30006, Murcia, M...|37.9971704|-1.0993366|
|[30100, Murcia, M...|38.0256612|-1.1640968|
|[30009, Murcia, M...|37.9887492|-1.1496969|
|[30008, Murcia, M...|37.9928939|-1.1317041|
|[30007, Murcia, M...|38.0077579|-1.0993366|
|[Murcia, MU, Regi...|37.9922399|-1.1306544|
|[30004, Murcia, M...|37.9822582|-1.1365014|
|[30003, Murcia, M...|37.9850434|-1.1221111|
|[Murcia, MU, Regi...|37.9922399|-1.1306544|
|[30152, Murcia, M...|37.9569734|-1.1496969|
|[30012, Murcia, M...|37.9651726|-1.1233101|
|[30011, Murcia, M...|37.9759009|-1.1089244|
|[30001, Murcia, M...|37.9856424|-1.1287061|
|[30010, Murcia, M...| 37.970285|-1.1424989|
+--------------------+----------+----------+

root
 |-- short_name: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- lat: double (nullable = true)
 |-- lng: double (nullable = true)

3 个答案:

答案 0 :(得分:1)

尝试一下:

df.selectExpr("short_name[0]", "lat", "lng")

第n个项目的选择实际上是SQL表达式,而不是列。因此,如果您想使用expr,也可以使用.select

df.select(expr("short_name[0]"), expr("lat"), expr("lng"))

答案 1 :(得分:1)

您可以在列上使用apply方法,也可以使用getItem

df.select(col("results.address_components.short_name")(0))

df.select(col("results.address_components.short_name").getItem(0))

答案 2 :(得分:1)

非常感谢您的帮助。两种方法都有效!

A2.select(col("results.address_components.short_name")(0),col("results.geometry.location.lat"),col("results.geometry.location.lng"))

A2.selectExpr("results.address_components.short_name[0]", "results.geometry.location.lat", "results.geometry.location.lng").show()

此外,我找到了一种使用UDF解决问题的方法:

val headValue = udf((arr: Seq[String]) => arr.head)
var dfElements3 = dfElements2.withColumn("CP",headValue(dfElements2("short_name")))
                             .select("CP","lat","lng")