舍入双精度值并转换为整数 [英] Round double values and cast as integers
本文介绍了舍入双精度值并转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 PySpark 中有一个数据框,如下所示.
I have a data frame in PySpark like below.
import pyspark.sql.functions as func
df = sqlContext.createDataFrame(
[(0.0, 0.2, 3.45631),
(0.4, 1.4, 2.82945),
(0.5, 1.9, 7.76261),
(0.6, 0.9, 2.76790),
(1.2, 1.0, 9.87984)],
["col1", "col2", "col3"])
df.show()
+----+----+-------+
|col1|col2| col3|
+----+----+-------+
| 0.0| 0.2|3.45631|
| 0.4| 1.4|2.82945|
| 0.5| 1.9|7.76261|
| 0.6| 0.9| 2.7679|
| 1.2| 1.0|9.87984|
+----+----+-------+
# round 'col3' in a new column:
df2 = df.withColumn("col4", func.round(df["col3"], 2))
df2.show()
+----+----+-------+----+
|col1|col2| col3|col4|
+----+----+-------+----+
| 0.0| 0.2|3.45631|3.46|
| 0.4| 1.4|2.82945|2.83|
| 0.5| 1.9|7.76261|7.76|
| 0.6| 0.9| 2.7679|2.77|
| 1.2| 1.0|9.87984|9.88|
+----+----+-------+----+
在上面的数据框中col4
是double
.现在我想将 col4
转换为 Integer
In the above data frame col4
is double
. Now I want to convert col4
as Integer
df2 = df.withColumn("col4", func.round(df["col3"], 2).cast('integer'))
+----+----+-------+----+
|col1|col2| col3|col4|
+----+----+-------+----+
| 0.0| 0.2|3.45631| 3|
| 0.4| 1.4|2.82945| 2|
| 0.5| 1.9|7.76261| 7|
| 0.6| 0.9| 2.7679| 2|
| 1.2| 1.0|9.87984| 9|
+----+----+-------+----+
但我想将 col4
值四舍五入到最接近的
But I want to round the col4
values to nearest
预期结果
+----+----+-------+----+
|col1|col2| col3|col4|
+----+----+-------+----+
| 0.0| 0.2|3.45631| 3|
| 0.4| 1.4|2.82945| 3|
| 0.5| 1.9|7.76261| 8|
| 0.6| 0.9| 2.7679| 3|
| 1.2| 1.0|9.87984| 10|
+----+----+-------+----+
我该怎么做?
推荐答案
您应该使用 round
函数,然后转换为整数类型.但是,不要对 round
函数使用第二个参数.通过在那里使用 2,它将四舍五入到 2 个小数位,cast
到整数将 向下舍入到最接近的数字.
You should use the round
function and then cast to integer type. However, do not use a second argument to the round
function. By using 2 there it will round to 2 decimal places, the cast
to integer will then round down to the nearest number.
改为使用:
df2 = df.withColumn("col4", func.round(df["col3"]).cast('integer'))
这篇关于舍入双精度值并转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文