[英]PySpark: How to update row if new value exists?
我在 pyspark 中有一个 DataFrame,如下所示:
ID | 约会时间 | 价格 | 数量旧 | 数量新增 |
---|---|---|---|---|
1个 | 20210203 | 200 | 20 | 30 |
1个 | 20210204 | 230 | 没有任何 | 没有任何 |
1个 | 20210205 | 225 | 没有任何 | 没有任何 |
1个 | 20210206 | 233 | 30 | 50 |
1个 | 20210207 | 220 | 没有任何 | 没有任何 |
2个 | 20210407 | 400 | 没有任何 | 没有任何 |
2个 | 20210408 | 410 | 90后 | 100 |
2个 | 20210409 | 415 | 没有任何 | 没有任何 |
2个 | 20210410 | 423 | 没有任何 | 没有任何 |
我想在其中添加一列,如下所示:
ID | 约会时间 | 价格 | 数量旧 | 数量新增 | 当前金额 |
---|---|---|---|---|---|
1个 | 20210203 | 200 | 20 | 30 | 30 |
1个 | 20210204 | 230 | 没有任何 | 没有任何 | 30 |
1个 | 20210205 | 225 | 没有任何 | 没有任何 | 30 |
1个 | 20210206 | 233 | 30 | 50 | 50 |
1个 | 20210207 | 220 | 没有任何 | 没有任何 | 50 |
2个 | 20210407 | 400 | 没有任何 | 没有任何 | 90后 |
2个 | 20210408 | 410 | 90后 | 100 | 100 |
2个 | 20210409 | 415 | 没有任何 | 没有任何 | 100 |
2个 | 20210410 | 423 | 没有任何 | 没有任何 | 100 |
我试过很多次像下面的代码但没有运气:
w = Window.partitionBy("id").orderBy(df_final.Datetime.desc())
df_final = df_final. \
withColumn("currentAmount",
when(col("amountNew").isNotNull(),
lag(col("amountNew")).over(w)) \
.otherwise(lag(col("amountOld")).over(w)))
我怎样才能做到这一点? 谢谢。
我们可以使用first
, last
来自超过window
的functions
w1 = Window.partitionBy('id').orderBy('Datetime').rowsBetween(Window.unboundedPreceding,Window.currentRow)
w2 = Window.partitionBy('id').orderBy('Datetime').rowsBetween(Window.currentRow,Window.unboundedFollowing)
df_final = df_final.withColumn('currentAmount',f.coalesce(f.last('amountNew',ignorenulls=True).over(w1),f.first('amountOld',ignorenulls=True).over(w2)))
dff.show()
+---+--------+-----+---------+---------+-------------+
| id|Datetime|price|amountOld|amountNew|currentAmount|
+---+--------+-----+---------+---------+-------------+
| 1|20210203| 200| 20| 30| 30|
| 1|20210204| 230| null| null| 30|
| 1|20210205| 225| null| null| 30|
| 1|20210206| 233| 30| 50| 50|
| 1|20210207| 220| null| null| 50|
| 2|20210407| 400| null| null| 90|
| 2|20210408| 410| 90| 100| 100|
| 2|20210409| 415| null| null| 100|
| 2|20210410| 423| null| null| 100|
+---+--------+-----+---------+---------+-------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.