我正在学习星星之火(scala),并且我正在创建一个带有派生列的dataframe。我正在努力找出最佳做法。
我的用例有两个派生列,它们寻找另一个列的值-例如-
if (col22 = "USD") then col1 = "US" elseif (col22 = "CDN" the col1 = "CA" else null)另一个用例是
if(col23 = "us" && col100 = "abc") then col2 = "10" else if (col23 = "us" && col100 = "bacd" && col99 is null then col2 = 11 else null)问题-我已经为上述计算编写了UDF函数。我想知道有什么更好的方法吗?编写udf函数是最佳实践。我将只在我的代码中使用这些函数一次。
我的Scala密码-
def udf1 = udf((col22: String){ (col22) match {
case col22 if (col22 == "USD") => "US"
case col22 if (col22 == "CDN") => "CA"
case _ => null } })
val df1= df.select($"col1", $"col2", udf1($"col22").as("newcol"), udf2($"col23", $"col100").as(newcol2))发布于 2016-06-18 18:36:49
你可以这样做:
val df1 = df.withColumn(
"newcol",
when($"col22" === "USD", lit("US")).otherwise(
when($"col22" === "CDN", lit("CA")).otherwise(lit(null))
)
)https://stackoverflow.com/questions/37899320
复制相似问题