考慮這個 MWE:
df = spark.createDataFrame([('A', 5, 0),('A',6, 0),('B',3, 0)], ['id', 'value', 'currentVersion'])
--- ----- --------------
| id|value|currentVersion|
--- ----- --------------
| A| 5| 0|
| A| 6| 0|
| B| 3| 0|
--- ----- --------------
有了這個預期的輸出
# --- ----- ----------
#| id|value|currentVersion|
# --- ----- ----------
#| A| 5| 0|
#| A| 6| 1|
#| B| 0| 0 |
# --- ----- ----------
如何在依賴 groupby 的同時獲得預期的輸出?
這適用于我的其他目的,但由于我需要合并 groupby 而失敗:
valueWhenTrue = 1
valueWhenFalse = 0
df = df.withColumn(
"currentVersion",
when(
F.col("TimeStamp") == df.agg({"TimeStamp": "max"}).collect()[0][0],
valueWhenTrue
).otherwise(valueWhenFalse)
)
uj5u.com熱心網友回復:
找到了一個適合我的答案:
# groupby -- find max time
window_var = Window().partitionBy('TicketNumber')
df = df.withColumn('maxModified', F.max('Modified').over(window_var))
# case when
valueWhenTrue = 1
valueWhenFalse = 0
df = df.withColumn(
"currentVersion",
when(
F.col("maxModified") == F.col('Modified'),
valueWhenTrue
).otherwise(valueWhenFalse)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/486900.html
標籤:阿帕奇火花 pyspark apache-spark-sql
