我正在使用 Pyspark >= 3.1 的 EMR 筆記本
我有 4 列:
- ID_CLIENT:客戶端的唯一索引
- IDX_TRX:交易的唯一索引。實際上這是一個字母數字列,索引不指示任何順序。本例中的數字索引是為了便于說明。
- dt:日期時間,交易日期
- AVERAGE_TRX:交易金額
我想計算以下列“AVERAGE_TRX”:
--------- -------- ---------- ----- ------------
|ID_CLIENT| IDX_TRX| dt|AMOUNT|AVERAGE_TRX|
--------- -------- ---------- ----- ------------
| A| 01|2018-06-14| 10| NULL| # 1st trx there are no records
| B| 01|2018-06-14| 5| NULL| # 1st trx there are no records
| A| 02|2018-06-15| 20| 10| # 10 / 1
| A| 03|2018-06-15| 30| 15| # (10 20) / 2
| B| 02|2018-06-16| 10| 5| # 5 / 1
| A| 04|2018-06-16| 20| 20| # (10 20 30) / 3
| A| 05|2018-06-17| 5| 20| # (10 20 30 20) / 4
| B| 03|2018-06-17| 10| 7.5| # (5 10) / 2
| A| 06|2018-06-18| 15| 17| # (10 20 30 20 5) / 5
| B| 04|2018-06-18| 10| 8.3333334| # (5 10 10) / 3
--------- -------- ---------- ----- ------------
如何計算最后一列?
先感謝您。
uj5u.com熱心網友回復:
試試這個 - 這會弄亂記錄的順序,但它應該具有所需的行值。
from pyspark.sql import Window
w = (Window.partitionBy('ID_CLIENT')
.orderBy('IDX_TRX')
.rowsBetween(Window.unboundedPreceding, -1)) # -1 is to do cumulative calculation up until the previous row.
df = df.withColumn('AVERAGE_TRX', avg('AMOUNT').over(w))
df.show()
--------- -------- ---------- ----- ------------
|ID_CLIENT| IDX_TRX| dt|AMOUNT|AVERAGE_TRX|
--------- -------- ---------- ----- ------------
| A| 01|2018-06-14| 10| null|
| A| 02|2018-06-15| 20| 10.0|
| A| 03|2018-06-15| 30| 15.0|
| A| 04|2018-06-16| 20| 20.0|
| A| 05|2018-06-17| 5| 20.0|
| A| 06|2018-06-18| 15| 17.0|
| B| 01|2018-06-14| 5| null|
| B| 02|2018-06-16| 10| 5.0|
| B| 03|2018-06-17| 10| 7.5|
| B| 04|2018-06-18| 10| 8.3333334|
--------- -------- ---------- ----- ------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/350178.html
