You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于多条件利用Spark DataFrame前一行值填充新列?

生成Spark DataFrame新列Column H的问题

免责声明:此问题可能为重复问题,但我未找到完全匹配的解决方案。若确认重复,请标注该问题并在评论中提供原问题链接。
我仍在学习Python DataFrame操作,此问题或许存在简单解法,但我暂未理清。

我拥有一个约1200万行的Spark DataFrame,包含多列。现需基于另外两列的最大值及新列前一行的派生值生成新列Column H。

输入数据

Column AColumn BColumn CColumn DColumn EColumn FColumn G
1Apr20223230
1May20223230
1Jun20223110
1Jul20223240
1Aug202232-10
1Sep20223830
1Oct20223230
1Nov20223200
1Dec20223200
1Jan20233260
1Feb20233250
1Mar20233260
1Apr20233270
1May20230000
2Apr20173230
2Apr20173230
2Apr20173110
2Apr20173240
2Apr201732-10
2Apr20173730

输出数据

Column AColumn BColumn CColumn DColumn EColumn FColumn GColumn HLogic
1Apr202232303Max of Column E and F
1May202232303Max of Column E and F and output of Column H previous row
1Jun202231103Max of Column E and F and output of Column H previous row
1Jul202232404Max of Column E and F and output of Column H previous row
1Aug202232-104Max of Column E and F and output of Column H previous row
1Sep202238308Max of Column E and F and output of Column H previous row
1Oct202202308Max of Column E and F and output of Column H previous row
1Nov202202008Max of Column E and F and output of Column H previous row
1Dec202200008Max of Column E and F and output of Column H previous row
1Jan2023006-36If Column G < 0 Max of Column E and F and (output of Column H previous row + Column G)
1Feb202302506Max of Column E and F and output of Column H previous row
1Mar202302606Max of Column E and F and output of Column H previous row
1Apr202300707Max of Column E and F and output of Column H previous row
1May202300007Max of Column E and F and output of Column H previous row
2Apr201732303Max of Column E and F
2Apr201732303Max of Column E and F and output of Column H previous row
2Apr201731103Max of Column E and F and output of Column H previous row
2Apr201732404Max of Column E and F and output of Column H previous row
2Apr201732-104Max of Column E and F and output of Column H previous row
2Apr201737307Max of Column E and F and output of Column H previous row

生成Column H的规则

  • DataFrame中Column A的不同值按年月升序排列;
  • 每个Column A不同值的首行,Column H取Column E与Column F的最大值;
  • 当Column G >=0时,后续行的Column H取Column E、Column F的最大值与前一行Column H值的最大值;
  • 当Column G <0时,Column H取Column E、Column F的最大值与(前一行Column H值 + Column G值)的最大值。

内容的提问来源于stack exchange,提问作者Raja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:10:21