您可以只使用可变参数:
val df = Seq(("a", "1", "c"), ("foo", "bar", "baz")).toDF("a", "b", "c")
val typedCols = Array("a", "cast(b as int) b", "c")
df.selectExpr(typedCols: _*).show
+---+----+---+
| a| b| c|
+---+----+---+
| a| 1| c|
|foo|null|baz|
+---+----+---+
但我个人更喜欢专栏:
val typedCols = Array($"a", $"b" cast "int", $"c")
df.select(typedCols: _*).show
如何获得包含通过输入的所有良好记录的 DataFrame 结果,然后将所有不良记录放入某种错误存储桶中?
失败的数据cast
is NULL
。要找到好的记录,请使用na.drop
:
val result = df.selectExpr(typedCols: _*)
val good = result.na.drop()
查找空头支票是否有NULL
import org.apache.spark.sql.functions.col
val bad = result.where(result.columns.map(col(_).isNull).reduce(_ || _))
要获取不匹配的数据:
-
If typedCols
are Seq[Column]
you can
df.where(typedCols.map(_.isNull).reduce(_ || _))
-
If typedCols
are Seq[String]
你可以:
import org.apache.spark.sql.functions.expr
df.where(typedCols.map(expr(_).isNull).reduce(_ || _))