我有一个 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”时向上舍入,“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()
和我得到
为什么会发生这种情况?我该如何修复它?
最佳答案
我可能没有完全理解 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|
+-------------------+
当使用简单的 if-else
语句就足够时,无需创建 UDF
。
# 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|
+-------------+
如果您只想使用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')))
关于python - 如何使用自定义 udf 实现对列进行舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54802904/