[英]Spark Java - Collect multiple columns into array column
我有一個包含多列的數據框:
| a | b | c | d |
-----------------
| 0 | 4 | 3 | 6 |
| 1 | 7 | 0 | 4 |
| 2 | 4 | 3 | 6 |
| 3 | 9 | 5 | 9 |
我現在想將[b,c,d]
成一個列。 但是, 我不知道,列的列表有多大 ,否則我可以使用UDF3來組合這三個。
所以期望的結果是:
| a | combined |
-----------------
| 0 | [4, 3, 6] |
| 1 | [7, 0, 4] |
| 2 | [4, 3, 6] |
| 3 | [9, 5, 9] |
我怎樣才能做到這一點?
非工作偽代碼:
public static Dataset<Row> mergeColumns(Dataset<Row> ds, List<String> columns) {
return ds.withColumn("combined", collectAsList(columns))
}
最壞情況的解決方法是關於輸入列數的switch語句,然后為每個輸入一個UDF,即2-20個輸入列,如果提供了更多輸入列,則拋出錯誤。
正如Ramesh在評論中提到的,你可以使用array
函數。 您只需要將列列表轉換為Column
數組。
public static Dataset<Row> mergeColumns(Dataset<Row> ds, List<String> columns) {
return ds.withColumn("combined", functions.array(columns.stream().map(functions::col).toArray(Column[]::new)))
}
val newDF = df.drop("a")
//create a new dataframe to get the combination of columns except the first column
val df2 = df.withColumn("combined", concat_ws(",",newDF.columns.map(collist =>
col(collist)): _*))
//new dataframe to select only the first and combined columns
val columnNames = Seq("a", "combined")
df2.select(columnNames.head, columnNames.tail:_*).show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.