簡體   English   中英

Apache Spark 根據列的不同值計算列值

[英]Apache Spark calculating column value on the basis of distinct value of columns

我正在處理下表,我想根據其他 2 個列的不同值計算一個新列(結果)。

| id1  | id2 | outcome
|  1   |  1  |  1
|  1   |  1  |  1
|  1   |  3  |  2
|  2   |  5  |  1 
|  3   |  1  |  1  
|  3   |  2  |  2
|  3   |  3  |  3

結果應根據id1id2的組合值從 1 開始以遞增順序開始。 任何提示如何在 Scala 中完成此操作。 在這種情況下, row_number在這里似乎沒有用。

這里的邏輯是,對於id1的每個唯一值,我們將使用 min( id2 ) 開始對結果進行編號,因為對應的id1被分配了值 1。

你可以試試 dense_rank()

以你的例子

      val df = sqlContext
        .read
        .option("sep","|")
        .option("header", true)
        .option("inferSchema",true)
        .csv("/home/cloudera/files/tests/ids.csv") // Here we read the .csv files
        .cache()

      df.show()
      df.printSchema()

      df.createOrReplaceTempView("table")
      sqlContext.sql(
        """
          |SELECT id1, id2, DENSE_RANK() OVER(PARTITION BY id1 ORDER BY id2) AS outcome
          |FROM table
          |""".stripMargin).show()

output

+---+---+-------+
|id1|id2|outcome|
+---+---+-------+
|  2|  5|      1|
|  1|  1|      1|
|  1|  1|      1|
|  1|  3|      2|
|  3|  1|      1|
|  3|  2|      2|
|  3|  3|      3|
+---+---+-------+

使用Window function 按first id對它們進行俱樂部( partition ),然后根據second id對每個partition進行order

現在您只需要在每個Window分區上分配一個等級 ( dense_rank )。

import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions.Window

df
.withColumn("outcome", dense_rank().over(Window.partitionBy("id1").orderBy("id2")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM