spark:有条件地向dataframe添加列

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

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

  1. A B C
  2. --------------
  3. 4 blah 2
  4. 2 3
  5. 56 foo 3

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

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

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

im9ewurl

im9ewurl1#

像这样的怎么样?

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

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

093gszye

093gszye2#

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

  1. // create some example data...BY DataFrame
  2. // note, third record has an empty string
  3. case class Stuff(a:String,b:Int)
  4. val d= sc.parallelize(Seq( ("a",1),("b",2),
  5. ("",3) ,("d",4)).map { x => Stuff(x._1,x._2) }).toDF
  6. // now the good stuff.
  7. import org.apache.spark.sql.functions.udf
  8. // function that returns 0 is string empty
  9. val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
  10. // create new dataframe with added column named "notempty"
  11. val r = d.select( $"a", $"b", func($"a").as("notempty") )
  12. scala> r.show
  13. +---+---+--------+
  14. | a| b|notempty|
  15. +---+---+--------+
  16. | a| 1| 1111|
  17. | b| 2| 1111|
  18. | | 3| 0|
  19. | d| 4| 1111|
  20. +---+---+--------+
展开查看全部
rmbxnbpk

rmbxnbpk3#

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

  1. val sqlContext = new SQLContext(sc)
  2. import sqlContext.implicits._ // for `toDF` and $""
  3. import org.apache.spark.sql.functions._ // for `when`
  4. val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
  5. .toDF("A", "B", "C")
  6. val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))
  7. ``` `newDf.show()` 显示

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

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

相关问题