如何在Scala Spark中对小数进行四舍五入
我有一个(大约100万个)Scala Spark数据框,其中包含以下数据:如何在Scala Spark中对小数进行四舍五入,scala,apache-spark,dataframe,concurrency,Scala,Apache Spark,Dataframe,Concurrency,我有一个(大约100万个)Scala Spark数据框,其中包含以下数据: id,score 1,0.956 2,0.977 3,0.855 4,0.866 ... 如何将分数离散/四舍五入至小数点后0.05位 预期结果: id,score 1,0.95 2,1.00 3,0.85 4,0.85 ... 希望避免使用UDF来最大限度地提高性能。您可以使用spark内置函数这样做 dataframe.withColumn("rounded_score", round(col("score")
id,score
1,0.956
2,0.977
3,0.855
4,0.866
...
如何将分数离散/四舍五入至小数点后0.05位
预期结果:
id,score
1,0.95
2,1.00
3,0.85
4,0.85
...
希望避免使用UDF来最大限度地提高性能。您可以使用spark内置函数这样做
dataframe.withColumn("rounded_score", round(col("score") * 100 / 5) * 5 / 100)
+---+-----+-------------+
| id|score|rounded_score|
+---+-----+-------------+
| 1|0.956| 0.95|
| 2|0.977| 1.0|
| 3|0.855| 0.85|
| 4|0.866| 0.85|
+---+-----+-------------+
您可以在转换为数据帧时指定模式 例如: 加载数据时,为customSchema中的列指定DecimalType(10,2)
id,score
1,0.956
2,0.977
3,0.855
4,0.866
...
import org.apache.spark.sql.types._
val mySchema = StructType(Array(
StructField("id", IntegerType, true),
StructField("score", DecimalType(10, 2), true)
))
spark.read.format("csv").schema(mySchema).
option("header", "true").option("nullvalue", "?").
load("/path/to/csvfile").show
答案可以更简单:
dataframe.withColumn("rounded_score", round(col("score"), 2))
有一种方法
def round(e: Column, scale: Int)
将e
的值四舍五入到scale
小数位,采用半舍五入模式
我认为这并不能真正回答问题,因为似乎解决方案应该精确到最接近的
0.05
。