首页 > 解决方案 > 动态循环所有列名的数据集

问题描述

我正在研究有大约 500 个列名的项目,但我需要coalesce在每个表名上应用函数。

df1图式

-id
-col1
...
-col500

df2图式

-id
-col1
...
-col500
Dataset<Row> newDS=  df1.join(df2, "id")
.select(
                df1.col("id"),
                functions.coalesce(df1.col("col1"),df2.col("col1")).as("col1"), 
                functions.coalesce(df1.col("col2"),df2.col("col2")).as("col2"),
...
functions.coalesce(df1.col("col500"),df2.col("col500")).as("col500"),
                )

        .show();

我试过的

 Dataset<Row> j1 =  df1.join(df2, "id");
Dataset<Row> gh1 = spark.emptyDataFrame();


    String[] f =  df1.columns();
     for(String h : f)
     {
         if(h == "id")
             gh1 = j1.select(df1.col("id"));
        else{
            gh1 = j1.select(functions.coalesce(df1.col(h),df2.col(h)).as(h));

        }


     }

     gh1.show();

标签: apache-sparkapache-spark-sqlapache-spark-dataset

解决方案


如果我理解正确,您有两个具有相同架构的数据框,并且您希望将它们的 500 列 2 x 2 合并,而无需编写所有内容。

这可以通过提供一系列列来轻松实现select。此外,由于select不接受列序列,而是接受可变数量的列参数,因此您需要添加: _*以让 scala 知道它需要将序列的所有元素视为单独的参数。

val cols = df1.columns.filter(_ != "id")
df1
    .join(df2, "id")
    .select(col("id") +: cols.map(n => coalesce(df1.col(n), df2.col(n)) as n) : _* )

推荐阅读