【问题标题】:Access to WrappedArray elements访问 WrappedArray 元素
【发布时间】:2017-11-12 02:13:14
【问题描述】:

我有一个 spark 数据框,这里是架构:

|-- eid: long (nullable = true)
|-- age: long (nullable = true)
|-- sex: long (nullable = true)
|-- father: array (nullable = true)
|    |-- element: array (containsNull = true)
|    |    |-- element: long (containsNull = true)

和一个行样本:。

df.select(df['father']).show()
+--------------------+
|              father|
+--------------------+
|[WrappedArray(-17...|
|[WrappedArray(-11...|
|[WrappedArray(13,...|
+--------------------+

类型是

DataFrame[father: array<array<bigint>>]

如何访问内部数组的每个元素?例如第一行的-17? 我尝试了不同的东西,比如df.select(df['father'])(0)(0).show(),但没有运气。

【问题讨论】:

    标签: python scala apache-spark pyspark


    【解决方案1】:

    如果我没记错的话,Python中的语法是

    df.select(df['father'])[0][0].show()
    

    df.select(df['father']).getItem(0).getItem(0).show()
    

    在此处查看一些示例:http://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=column#pyspark.sql.Column

    【讨论】:

      【解决方案2】:

      scala中的解决方案应该是

      import org.apache.spark.sql.functions._
      val data =  sparkContext.parallelize("""{"eid":1,"age":30,"sex":1,"father":[[1,2]]}""" :: Nil)
      val dataframe = sqlContext.read.json(data).toDF()
      

      数据框看起来像

      +---+---+---+--------------------+
      |eid|age|sex|father              |
      +---+---+---+--------------------+
      |1  |30 |1  |[WrappedArray(1, 2)]|
      +---+---+---+--------------------+
      

      解决办法应该是

      dataframe.select(col("father")(0)(0) as("first"), col("father")(0)(1) as("second")).show(false)
      

      输出应该是

      +-----+------+
      |first|second|
      +-----+------+
      |1    |2     |
      +-----+------+
      

      【讨论】:

      • 为什么要用array 函数包裹你的专栏? dataframe.select($"father"(0)(0))dataframe.select(col("father")(0)(0)) 也可以正常工作
      【解决方案3】:

      另一个 scala 答案如下所示:

      df.select(col("father").getItem(0) as "father_0", col("father").getItem(1) as "father_1")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-07
        • 2013-04-14
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 2019-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多