通过迭代Scala列名列表中的列,从Spark数据框中删除多个列

Ram*_*esh 3 scala apache-spark apache-spark-sql

我有一个数据框,其列数约为400,我想根据我的要求删除100列.所以我创建了一个包含100个列名的Scala列表.然后我想迭代一个for循环来实际删除每个for循环迭代中的列.

下面是代码.

final val dropList: List[String] = List("Col1","Col2",...."Col100”)

def drpColsfunc(inputDF: DataFrame): DataFrame = { 
    for (i <- 0 to dropList.length - 1) {
        val returnDF = inputDF.drop(dropList(i))
    }
    return returnDF
}

val test_df = drpColsfunc(input_dataframe) 

test_df.show(5)
Run Code Online (Sandbox Code Playgroud)

Ram*_*esh 17

回答:

val colsToRemove = Seq("colA", "colB", "colC", etc) 

val filteredDF = df.select(df.columns .filter(colName => !colsToRemove.contains(colName)) .map(colName => new Column(colName)): _*) 
Run Code Online (Sandbox Code Playgroud)

  • `df.drop(colsToRemove : _*)` 这是一个更简单|更干净的解决方案。 (2认同)

Blo*_*Pig 17

如果您只想做一些比删除多个命名列更复杂的事情,而不是按特定条件选择它们,您可以简单地执行以下操作:

df.drop("colA", "colB", "colC")
Run Code Online (Sandbox Code Playgroud)


小智 8

这应该可以正常工作:

val dropList : List[String]  |
val df : DataFrame  |
val test_df = df.drop(dropList : _*) 
Run Code Online (Sandbox Code Playgroud)