[英]How to shift a column based on other columns in pyspark
我需要根據 pyspark 中數據框中的 Col2 和 Col3 列將 Col4 向左移動。 Col4 值應在 col2 連續更改時更改。 Col3 主要跟蹤 Col2 值的新序列。 Col1 還應該對最終輸出進行分區。 輸出應該類似於 shift_col4。
ID Col1 Col2 Col3 Col4 shift_col4
1 1 10 1 4 null
2 1 11 1 8 4
3 1 12 1 12 8
4 1 1 2 16 12
5 1 3 2 20 16
4 2 1 1 16 null
5 2 4 1 20 16
我不知道您是否只需要查看 Col2 是否更改為移位(推送)Col4,需要更多信息,但我這樣做是基於 Col2 每次更改時都會將 Col4 的值向前推。
w = Window.partitionBy('Col1').orderBy('ID', 'Col1')
df = df.withColumn('shift_4', f.when(f.lag('Col2').over(w) != f.col('Col2'), f.lag('Col4').over(w)))
df.show()
+---+----+----+----+----+-------+
| ID|Col1|Col2|Col3|Col4|shift_4|
+---+----+----+----+----+-------+
| 1| 1| 10| 1| 4| null|
| 2| 1| 11| 1| 8| 4|
| 3| 1| 12| 1| 12| 8|
| 4| 1| 1| 2| 16| 12|
| 5| 1| 2| 2| 20| 16|
| 4| 2| 1| 1| 16| null|
| 5| 2| 2| 1| 20| 16|
+---+----+----+----+----+-------+
如果您需要跟蹤 Col2 序列並且只是在更改中斷時進行更改,您可以創建另一個窗口函數並使用 rank 來查看它,然后將其包含在when函數的邏輯中。 在這種情況下,您可以查看這個問題,它可能會對您有所幫助: Counting Continuous occurrences of a specific value in PySpark
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.