gpt4 book ai didi

python - 舍入 double 值并转换为整数

转载 作者:太空狗 更新时间:2023-10-30 02:15:22 26 4
gpt4 key购买 nike

我在 PySpark 中有一个数据框,如下所示。

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|
+----+----+-------+----+

在上面的数据框中 col4double。现在我想将 col4 转换为 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 值四舍五入到最接近的值

预期结果

+----+----+-------+----+
|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,它将四舍五入到小数点后两位,cast 到整数然后将向下舍入到最接近的数字。

改为使用:

df2 = df.withColumn("col4", func.round(df["col3"]).cast('integer'))

关于python - 舍入 double 值并转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com