如何使用自定义udf实现来舍入列

问题描述 投票:1回答:1

我有一个pyspark数据框,如:

+-------------------+
|      to_return_day|
+-------------------+
|          -2.003125|
| -20.96738425925926|
| -2.332546296296296|
| -2.206770833333333|
|-2.9733564814814817|
| 54.71157407407407|
| 51.70229166666667|
|48.666354166666665|
| 9.665497685185185|
| 49.56260416666667|
| 66.68983796296297|
| 49.80550925925926|
|  66.6899074074074|

并且我想使用udf在“to_return_day”> 0时实现舍入,并在“to_return_day”<0时使用向下舍入。

我的代码:

from pyspark.sql.functions import udf
@udf("double")
def floor_ceil(col_day):
   if col_day > 0:
      return ceil(col_day)
   else :
       return floor(col_day)
 spark.udf.register("floor_ceil", floor_ceil)
patron_lending_time.withColumn("to_return_day_round",ceil(col("to_return_day")))\
               .show()

而我的到来

enter image description here

为什么会这样?我该如何解决?

python pyspark user-defined-functions floor ceil
1个回答
0
投票

我可能还没有完全理解Q OP已发布。根据我的理解,输出OP想要的是 -

1)对于正值(大于等于0),最接近该数值的整数值,例如;对于2.34,它将是3。

2)对于负值,最接近该数字的整数值,例如;对于-2.34,它将是-3。

# Creating the DataFrame
values = [(-2.003125,),(-20.96738425925926,),(-2.332546296296296,),(-2.206770833333333,),
          (-2.9733564814814817,),(54.71157407407407,),(51.70229166666667,),(48.666354166666665,),
          (9.665497685185185,),(49.56260416666667,),(66.68983796296297,),(49.80550925925926,),
          (66.6899074074074,),]
df = sqlContext.createDataFrame(values,['to_return_day',])
df.show()
+-------------------+
|      to_return_day|
+-------------------+
|          -2.003125|
| -20.96738425925926|
| -2.332546296296296|
| -2.206770833333333|
|-2.9733564814814817|
|  54.71157407407407|
|  51.70229166666667|
| 48.666354166666665|
|  9.665497685185185|
|  49.56260416666667|
|  66.68983796296297|
|  49.80550925925926|
|   66.6899074074074|
+-------------------+

当使用简单的UDF语句时,无需创建if-else

# Importing relevant functions
from pyspark.sql.functions import ceil, floor, when
df = df.withColumn('to_return_day',when(col('to_return_day') >=0 , ceil(col('to_return_day'))).otherwise(floor(col('to_return_day'))))
df.show()
+-------------+
|to_return_day|
+-------------+
|           -3|
|          -21|
|           -3|
|           -3|
|           -3|
|           55|
|           52|
|           49|
|           10|
|           50|
|           67|
|           50|
|           67|
+-------------+

文档:ceilfloor

如果您只想使用UDF,那么以下代码将起作用。

# Import relevant functions and packages.
from pyspark.sql.functions import udf, col
import math
# Defining a UDF
def round_udf(c):
    if c < 0:
        return math.floor(c)
    else:
        return math.ceil(c)

round_udf = udf(round_udf,IntegerType())

df = df.withColumn('to_return_day',round_udf(col('to_return_day')))
© www.soinside.com 2019 - 2024. All rights reserved.