首页 > 解决方案 > 在数据框 (Spark) 中选择列时在其间添加一个空列

问题描述

我正在尝试在数据框选择语句的两列之间添加一个空列。

使用该withColumn功能,我只能追加作为结束列,但我需要中间的空列(第 3 列和第 6 列),如下所示。

val product1 = product.select("_c1","_c2"," ","_c4", "_c5", "_c5", " ", "c6")

我尝试withColumnselect语句中间使用,如下所示,它给出了错误:

val product1 = product.select("_c1","_c2",product.withColumn("NewCol",lit(None).cast("string")),"_c4", "_c5", "_c5", " ", "c6")

>error: overloaded method value select with alternatives:
  (col: String,cols: String*)org.apache.spark.sql.DataFrame <and>
  (cols: org.apache.spark.sql.Column*)org.apache.spark.sql.DataFrame
 cannot be applied to (String, String, String, String, String, String, String, String, org.apache.spark.sql.DataFrame, String)

如果有任何建议,请告诉我。谢谢

标签: scalaapache-sparkapache-spark-sql

解决方案


为了在数据框中选择列,可以使用字符串(列名)或列(Column类型)作为输入。从文档中:

def select(col: String, cols: String*): DataFrame  
Selects a set of columns.
def select(cols: Column*): DataFrame  
Selects a set of column based expressions.

但是,这些不能混用。在这种情况下,请使用selectwithColumn类型。要获取特定名称的列,请使用col函数或$(在导入 spark 隐式之后)。

val spark = SparkSession()....
import spark.implicits._

val product1 = product.select($"_c1", $"_c2", lit(" ").as("newCol1"), $"_c4", $"_c5", $"_c5", lit(" ").as("newCol2"), $"c6")

推荐阅读