我想將訂單數量從 1 轉移到 7。這??是我的 python代碼:
def make_features(data, max_lag):
for lag in range(1, max_lag 1):
data['lag_{}'.format(lag)] = data['num_orders'].shift(lag)
make_features(df, 7)
我嘗試在 Pyspark 中做同樣的想法:代碼:
def make_features(data, max_lag):
for lag in range(1, max_lag 1):
data['lag_{}'.format(lag)] = data['num_orders'].shift(lag)
make_features(df, 7)
我收到此錯誤:
TypeError: 'int' object is not callable
Traceback (most recent call last):
TypeError: 'int' object is not callable
我也試試這段代碼:
for lag in range(1, 8):
window = Window.orderBy("date")
lagCol = lag(col("num_orders"), n).over(window)
df.withColumn(f"LagCol_{n}", lagCol)
這只是移動了 1 個單位:
預期結果:

uj5u.com熱心網友回復:
在 PySpark 中,沒有shift您期望的功能,并且您在使用lag. 但是這里有一個小技巧,當你必須做lag_2基于lag_1等等的時候。
from pyspark.sql import functions as F
from pyspark.sql import Window as W
df = df.withColumn('lag_0', F.col('num_orders'))
for lag in range(1, 8):
df = (df
.withColumn(f'lag_{lag}', F
.lag(f'lag_{lag - 1}')
.over(W
.partitionBy(F.lit(1))
.orderBy('date')
)
)
)
---- ---------- ----- ----- ----- ----- ----- ----- ----- -----
|date|num_orders|lag_0|lag_1|lag_2|lag_3|lag_4|lag_5|lag_6|lag_7|
---- ---------- ----- ----- ----- ----- ----- ----- ----- -----
| 1| 124| 124| null| null| null| null| null| null| null|
| 2| 85| 85| 124| null| null| null| null| null| null|
| 3| 71| 71| 85| 124| null| null| null| null| null|
| 4| 66| 66| 71| 85| 124| null| null| null| null|
| 5| 43| 43| 66| 71| 85| 124| null| null| null|
| 6| 6| 6| 43| 66| 71| 85| 124| null| null|
| 7| 12| 12| 6| 43| 66| 71| 85| 124| null|
---- ---------- ----- ----- ----- ----- ----- ----- ----- -----
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437350.html
