scala 将dataframe列中的负值更改为零值

rbl8hiat  于 2023-08-05  发布在  Scala
关注(0)|答案(1)|浏览(139)

我有这样一个数据框:

Col1   Col2   Col3   Col4      Col5      Col6
1   1982      0      0   -211       107         0
2   4412      0    989      0       296         0
3      0  -5051      0   -267       389       920
4      0  -2983      0   -215         0      1639
5      0  -1326      0   -861         0         0
6   3722      0     89      0       243     13349

字符串
如何将负值更改为零值?使用Scala和spark
预期结果

Col1   Col2   Col3   Col4      Col5      Col6
    1   1982      0      0     0       107         0
    2   4412      0    989     0       296         0
    3      0      0      0     0       389       920
    4      0      0      0     0         0      1639
    5      0      0      0     0         0         0
    6   3722      0     89     0       243     13349

mbskvtky

mbskvtky1#

在这种情况下,尝试使用Case when语句,检查值是否为< 0,否则为0,保持值不变。

Example:

import org.apache.spark.sql.functions._
val df = Seq((1,-23,-999)).toDF("a","b","c")
//df.select(df.columns.head,df.columns.tail:_*).show()
val df1 = df
  .columns
  .foldLeft(df) { (df, colName) =>
    df
      .withColumn(colName, when(col(colName).cast("int")<0,lit(0)).otherwise(col(colName)))
  }

df1.show(10,false)
//+---+---+---+
//|a  |b  |c  |
//+---+---+---+
//|1  |0  |0  |
//+---+---+---+

字符串

相关问题