[英]How to format a column in Spark DataFrame
有一个Spark DataFrame调用df,如下所示:
+---+---+
| c1| c2|
+---+---+
| 1| 6|
| 2| 7|
| 3| 8|
| 4| 9|
| 5| 10|
| 6| 11|
| 7| 12|
| 8| 13|
| 9| 14|
+---+---+
而且我想生成一个新的DataFrame来获取c1和c2的分数,结果应该是这样的:
+---+---+------+
| c1| c2| c3|
+---+---+------+
| 9| 14|0.6429|
| 8| 13|0.6154|
| 7| 12|0.5833|
| 6| 11|0.5455|
| 5| 10|0.5000|
| 4| 9|0.4444|
| 3| 8|0.3750|
| 2| 7|0.2857|
| 1| 6|0.1667|
+---+---+------+
但是,当我使用代码时
res.withColumn("c3", col("c1")/col("c2")).orderBy(col("c3").desc).show()
我有:
+---+---+-------------------+
| c1| c2| c3|
+---+---+-------------------+
| 9| 14| 0.6428571428571429|
| 8| 13| 0.6153846153846154|
| 7| 12| 0.5833333333333334|
| 6| 11| 0.5454545454545454|
| 5| 10| 0.5|
| 4| 9| 0.4444444444444444|
| 3| 8| 0.375|
| 2| 7| 0.2857142857142857|
| 1| 6|0.16666666666666666|
+---+---+-------------------+
如何在无需生成另一个DataFrame的情况下将c3格式化为所需格式? (我想只用一行代码从df中获得结果,我怎么能做到这一点?)
您可以使用format_number函数作为
import org.apache.spark.sql.functions._
res.withColumn("c3", format_number(col("c1")/col("c2"), 4)).orderBy(col("c3").desc).show()
另外,您也可以将结果转换为正确的DecimalType()
:
import org.apache.spark.sql.functions.{col}
import org.apache.spark.sql.types._
res.withColumn("c3", (col("c1")/col("c2"))
.cast(DecimalType(4,4)))
.orderBy(col("c3").desc).show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.