apache-spark - 动态循环所有列名的数据集
问题描述
我正在研究有大约 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();
解决方案
如果我理解正确,您有两个具有相同架构的数据框,并且您希望将它们的 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) : _* )
推荐阅读
- python - knn图像分类,准确率差
- awkward-array - 保存笨拙1数组的最佳方法?
- android - 通话中对 Android 音频路由有何影响?
- android - Android CameraX 返回成功但不保存图片
- python - 解密在 O(N) 时间内运行的基数排序的字符串排序版本
- python - 使用 Gekko 的模拟模式 - 初始值为零的变量 C2 (NH2Cl) 不起作用 - 为什么?
- r - 将单个表中的两列合并为一列
- c# - HtmlRendererCore.PdfSharpCore 弹性框
- google-play - 在 Google Play 和 App Store 中获取当前应用版本
- r - 如何在ggplot的图形上写出某个变量的值?