有人可以解释下面的代码片段中发生了什么吗?我试图理解下面的 Scala 代码
Can someone explain what is happening in the below snipped of code? I am trying to understand the below Scala code
import org.apache.spark.sql.functions._
def expr(myCols: Set[String], allCols: Set[String]) =
allCols.toList.map {
case x if myCols.contains(x) => col(x)
case x => lit(null).as(x)
}
这个方法 returns 一个 Columns 的列表,当你使用这个列表到数据框的 select 列时,一些列被设置为 null
.
allCols
应包含数据框的所有列,myCols
应包含您要保留的列。 myCols
中未包含的所有其他列将设置为 null
:
val df = spark.createDataFrame(Seq((1,2,3),(4,5,6),(7,8,9))).toDF("a","b","c")
df.show
val columns = expr(Set("a"), df.columns.toSet)
df.select(columns:_*).show
将打印
+---+---+---+
| a| b| c|
+---+---+---+
| 1| 2| 3|
| 4| 5| 6|
| 7| 8| 9|
+---+---+---+
+---+----+----+
| a| b| c|
+---+----+----+
| 1|null|null|
| 4|null|null|
| 7|null|null|
+---+----+----+
在您的方法内部,allCols
的每个条目要么映射到实际列,要么通过使用 Scala 的 pattern matching 魔法映射到 null
文字。
import org.apache.spark.sql.functions._
def expr(myCols: Set[String], allCols: Set[String]) =
allCols.toList.map {
case x if myCols.contains(x) => col(x)
case x => lit(null).as(x)
}
这个方法 returns 一个 Columns 的列表,当你使用这个列表到数据框的 select 列时,一些列被设置为 null
.
allCols
应包含数据框的所有列,myCols
应包含您要保留的列。 myCols
中未包含的所有其他列将设置为 null
:
val df = spark.createDataFrame(Seq((1,2,3),(4,5,6),(7,8,9))).toDF("a","b","c")
df.show
val columns = expr(Set("a"), df.columns.toSet)
df.select(columns:_*).show
将打印
+---+---+---+
| a| b| c|
+---+---+---+
| 1| 2| 3|
| 4| 5| 6|
| 7| 8| 9|
+---+---+---+
+---+----+----+
| a| b| c|
+---+----+----+
| 1|null|null|
| 4|null|null|
| 7|null|null|
+---+----+----+
在您的方法内部,allCols
的每个条目要么映射到实际列,要么通过使用 Scala 的 pattern matching 魔法映射到 null
文字。