【发布时间】:2019-07-09 15:44:58
【问题描述】:
我想创建一个火花数据框的新列,其中包含已存在列的四舍五入值。 “em”列的类型是浮点数。
我已经检查了各种帖子,但无法弄清楚。包括以下链接:Trouble With Pyspark Round Function
这是我的代码:
import pyspark.sql.functions as f
df = df.withColumn("rounded", f.round(f.col("em"), 3))
df.show()
新生成的列“rounded”与原始列“em”完全相同。我正在 Cloudera 集群上的 Zeppelin Notebook 中使用 pyspark 2.3.0 版。
更新:
尝试了以下方法:
%pyspark
s2_em = s2.select('em')
print "Datatype:", type(s2_em)
s2_em.printSchema()
s2_em = s2_em.withColumn('rounded', f.round(f.col('em'), 3))
s2_em = s2_em.withColumn('plus', f.col('em') + f.col('rounded'))
s2_em = s2_em.withColumn('minus', f.col('em') - f.col('rounded'))
s2_em = s2_em.withColumn('multiplication', f.col('em') * f.col('rounded'))
s2_em.limit(5).show()
这会产生以下结果,但四舍五入仍然不起作用。还有其他提示吗?:
Datatype: <class 'pyspark.sql.dataframe.DataFrame'>
root |-- em: float (nullable = true)
+------------+------------+------------+-----+--------------+
| em| rounded| plus|minus|multiplication|
+------------+------------+------------+-----+--------------+
|1.14209626E9|1.14209626E9|2.28419251E9| 0.0| 1.3043839E18|
|1.25046528E9|1.25046528E9|2.50093056E9| 0.0| 1.56366345E18|
| 9.5720672E8| 9.5720672E8|1.91441344E9| 0.0| 9.1624469E17|
| 1.1392649E9| 1.1392649E9|2.27852979E9| 0.0| 1.29792455E18|
|1.29539699E9|1.29539699E9|2.59079398E9| 0.0| 1.67805334E18|
+------------+------------+------------+-----+--------------+
【问题讨论】:
-
df = df.withColumn("rounded", f.round(f.col("em"), 3)).show()中的显示不正确,你必须删除它
标签: apache-spark pyspark apache-spark-sql rounding