python - 如何在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()))
并且仍然给出类似的输出
解决方案
演员工作正常 -
数据准备
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|
+---+------------+------+----------------+
推荐阅读
- plot - 我们如何一起使用 Dask 和 Datashader?
- asp.net-core - 如何将 Aurelia.js 网站分成两部分
- java - 在没有调试器的情况下控制 java 程序的执行
- c# - 获取 System.Data.OleDb.OleDbException:“没有为一个或多个必需参数提供值。” 使用 c# 从 Excel 工作表中读取数据时
- asp.net - 在 AspNet MVC 中显示用户全名而不是用户电子邮件
- mysql - 如何从 SQL 中的子查询中选择最大值以显示结果
- android - 在 onResume 等非活动类上获取回调
- db2 - 当我从 RPG 程序调用 JAVA 类时,我遇到错误说“java.lang.NoClassDefFoundError
- java - 删除标题文本 aspose 单元格
- javascript - 如何在不重新加载的情况下更新页面上的信息