【问题标题】:How to extract particular element from the column for each row?如何从每一行的列中提取特定元素?
【发布时间】:2018-05-06 09:30:39
【问题描述】:

我在 Spark 2.2.0 和 Scala 2.11.8 中有以下 DataFrame。

+----------+-------------------------------+
|item      |        other_items            |
+----------+-------------------------------+
|  111     |[[444,1.0],[333,0.5],[666,0.4]]|
|  222     |[[444,1.0],[333,0.5]]          |
|  333     |[]                             |
|  444     |[[111,2.0],[555,0.5],[777,0.2]]|

我想得到以下DataFrame:

+----------+-------------+
|item      | other_items |
+----------+-------------+
|  111     | 444         |
|  222     | 444         |
|  444     | 111         |

所以,基本上,我需要为每一行从other_items 中提取第一个item。另外,我需要忽略那些在other_products 中有空数组[] 的行。

我该怎么做?

我尝试了这种方法,但它没有给我预期的结果。

result = df.withColumn("other_items",$"other_items"(0))

printScheme 给出以下输出:

 |-- item: string (nullable = true)
 |-- other_items: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- _1: string (nullable = true)
 |    |    |-- _2: double (nullable = true)

【问题讨论】:

    标签: scala apache-spark spark-dataframe


    【解决方案1】:

    像这样:

    val df = Seq(
      ("111", Seq(("111", 1.0), ("333", 0.5), ("666", 0.4))), ("333", Seq())
    ).toDF("item", "other_items")
    
    
    df.select($"item", $"other_items"(0)("_1").alias("other_items"))
      .na.drop(Seq("other_items")).show
    

    其中第一个apply$"other_items"(0))选择数组的第一个元素,第二个apply_("_1")selects_1字段,na.drop删除由empty引入的nulls数组。

    +----+-----------+
    |item|other_items|
    +----+-----------+
    | 111|        111|
    +----+-----------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      相关资源
      最近更新 更多