簡體   English   中英

將列表添加到 Scala/Spark 中的數據幀,以便將每個元素添加到單獨的行

[英]Adding a list to a dataframe in Scala / Spark such that each element is added to a separate row

比如說我有一個以下格式的數據框(實際上是更多的文檔):

df.show()

//output
    +-----+-----+-----+
    |doc_0|doc_1|doc_2|
    +-----+-----+-----+
    |  0.0|  1.0|  0.0|
    +-----+-----+-----+
    |  0.0|  1.0|  0.0|
    +-----+-----+-----+
    |  2.0|  0.0|  1.0|
    +-----+-----+-----+

// ngramShingles is a list of shingles
println(ngramShingles)

//output
    List("the",  "he ", "e l")

其中ngramShingles長度等於數據幀列的大小。

我將如何獲得以下輸出?

// Desired Output
+-----+-----+-----+-------+
|doc_0|doc_1|doc_2|shingle|
+-----+-----+-----+-------+
|  0.0|  1.0|  0.0|  "the"|
+-----+-----+-----+-------+
|  0.0|  1.0|  0.0|  "he "|
+-----+-----+-----+-------+
|  2.0|  0.0|  1.0|  "e l"|
+-----+-----+-----+-------+

我試圖通過以下代碼行添加一列:

val finalDf = df.withColumn("shingle", typedLit(ngramShingles))

但這給了我這個輸出:

+-----+-----+-----+-----------------------+
|doc_0|doc_1|doc_2|                shingle|
+-----+-----+-----+-----------------------+
|  0.0|  1.0|  0.0|  ("the", "he ", "e l")|
+-----+-----+-----+-----------------------+
|  0.0|  1.0|  0.0|  ("the", "he ", "e l")|
+-----+-----+-----+-----------------------+
|  2.0|  0.0|  1.0|  ("the", "he ", "e l")|
+-----+-----+-----+-----------------------+

我嘗試了其他一些解決方案,但實際上我嘗試過的任何東西都沒有接近。 基本上,我只想將新列添加到 DataFrame 中的每一行。

這個問題展示了如何做到這一點,但兩個答案都依賴於已經存在一列。 我不認為我可以將這些答案應用於我有數千列的情況。

您可以從列表中制作數據框,然后將兩個數據框連接在一起。 要加入,您需要添加一個額外的列,用於加入(以后可以刪除):

val listDf = List("the",  "he ", "e l").toDF("shingle")

val result = df.withColumn("rn", monotonically_increasing_id())
   .join(listDf.withColumn("rn", monotonically_increasing_id()), "rn")
   .drop("rn")

結果:

+-----+-----+-----+-------+
|doc_0|doc_1|doc_2|shingle|
+-----+-----+-----+-------+
|  0.0|  1.0|  0.0|    the|
|  0.0|  1.0|  0.0|    he |
|  2.0|  0.0|  1.0|    e l|
+-----+-----+-----+-------+

暫無
暫無

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

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