python转化为整数_python – 舍入double值并转换为整数

我在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|

+----+----+-------+----+

在上面的数据框架中,col4是双倍的.现在我想将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|

+----+----+-------+----+

我怎样才能做到这一点?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值