spark:有条件地向dataframe添加列

7fhtutme  于 2021-07-09  发布在  Spark
关注(0)|答案(3)|浏览(396)

我正在尝试获取输入数据:

A    B       C
--------------
4    blah    2
2            3
56   foo     3

并根据b是否为空在末尾加一列:

A    B       C     D
--------------------
4    blah    2     1
2            3     0
56   foo     3     1

我可以通过将输入dataframe注册为temp表,然后键入sql查询来轻松地完成这项工作。
但我很想知道如何只使用scala方法而不必在scala中键入sql查询。
我试过了 .withColumn 但我不能让它做我想做的事。

im9ewurl

im9ewurl1#

像这样的怎么样?

val newDF = df.filter($"B" === "").take(1) match {
  case Array() => df
  case _ => df.withColumn("D", $"B" === "")
}

使用 take(1) 应该有一个最小的打击

093gszye

093gszye2#

我的错是,我漏掉了问题的一部分。
最好,最干净的方法是使用 UDF . 代码内的解释。

// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
     ("",3) ,("d",4)).map { x => Stuff(x._1,x._2)  }).toDF

// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty 
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )

    scala> r.show
+---+---+--------+
|  a|  b|notempty|
+---+---+--------+
|  a|  1|    1111|
|  b|  2|    1111|
|   |  3|       0|
|  d|  4|    1111|
+---+---+--------+
rmbxnbpk

rmbxnbpk3#

尝试 withColumn 使用函数 when 具体如下:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`

val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
    .toDF("A", "B", "C")

val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))
``` `newDf.show()` 显示

+---+----+---+---+
| A| B| C| D|
+---+----+---+---+
| 4|blah| 2| 1|
| 2| | 3| 0|
| 56| foo| 3| 1|
|100|null| 5| 0|
+---+----+---+---+

我添加了 `(100, null, 5)` 用于测试的行 `isNull` 案例。
我试过这个密码 `Spark 1.6.0` 但正如《美国法典》中所说 `when` ,它在之后的版本上工作 `1.4.0` .

相关问题