【问题标题】:How to join Dataframe with one-column dataset without using column names in dataset如何在不使用数据集中的列名的情况下将 Dataframe 与一列数据集连接
【发布时间】:2021-05-03 19:21:09
【问题描述】:
让我们考虑一下:
val columnNames: Seq[String] = Seq[String]("col_1") // column present in DataFrame df
df.join(usingColumns = columnNames, right = ds)) // ds is some dataset that has exactly one column.
// the problem is about the fact that I don't know name of this column? I only know that
// df.col("col_1") and ds.col(???)` has the same types.
可以这样加入吗?
【问题讨论】:
标签:
scala
dataframe
apache-spark
join
dataset
【解决方案1】:
您可以将数据集的列名更改为col_1:
val result = df.join(ds.withColumnRenamed(ds.columns(0), "col_1"), "col_1", "right")
【解决方案2】:
假设第一个数据帧中的“col_1”将始终连接到 ds 数据帧中的单列,您可以使用单列重命名 ds 数据帧中的列,如下所示。那么你使用名字的加入只需要引用“col_1”
// set the name of the column in ds to col_1
val ds2 = ds.toDF("col_1")
【解决方案3】:
你可以使用类似的东西:
包工具
object Extensions {
implicit class DataFrameExtensions(df: DataFrame) {
def selecti(indices: Int*) = {
val cols = df.columns
df.select(indices.map(cols(_)):_*)
}
}
}
然后使用它按数字选择列:
import utils.Extensions._
df.selecti(1,2,3)