首页 > 解决方案 > 如何在pyspark中使累积和仍然是整数

问题描述

这是我当前的输出

+---+------------+
| ix|last_x_month|
+---+------------+
|  1|         1.0|
|  1|         2.0|
|  1|         3.0|
|  1|         4.0|
|  1|         5.0|
+---+------------+

这是我的代码

import sys
import pyspark.sql.functions as F
from pyspark.sql.window import Window
df = df.withColumn('last_x_month', F.sum(datamonthly.ix).over(Window.partitionBy().orderBy().rowsBetween(-sys.maxsize, 0)))

这是我的预期输出(仍然是整数)

+---+------------+
| ix|last_x_month|
+---+------------+
|  1|           1|
|  1|           2|
|  1|           3|
|  1|           4|
|  1|           5|
+---+------------+

注意:我也已经尝试通过使用转换为整数datamonthly.withColumn("last_x_month",datamonthly.last_x_month.cast(IntegerType()))

并且仍然给出类似的输出

标签: pythondataframepyspark

解决方案


演员工作正常 -

数据准备

input_list = [(1.0,),(1.0,),(1.0,),(1.0,),(1.0,)]

sparkDF = sql.createDataFrame(input_list, ['ix'])

sparkDF.show()

+---+
| ix|
+---+
|1.0|
|1.0|
|1.0|
|1.0|
|1.0|
+---+

窗户和铸件

window = Window.partitionBy().orderBy().rowsBetween(-sys.maxsize, 0)

sparkDF = sparkDF.withColumn('last_x_month', F.sum('ix').over(window))

to_convert = ['ix','last_x_month']

sparkDF = reduce(lambda df, x: df.withColumn(f'{x}_int',F.col(x).cast(IntegerType())), to_convert, sparkDF)

sparkDF.show()

+---+------------+------+----------------+
| ix|last_x_month|ix_int|last_x_month_int|
+---+------------+------+----------------+
|1.0|         1.0|     1|               1|
|1.0|         2.0|     1|               2|
|1.0|         3.0|     1|               3|
|1.0|         4.0|     1|               4|
|1.0|         5.0|     1|               5|
+---+------------+------+----------------+

推荐阅读