[英]Pyspark apply a function on dataframe
我的python方法如下;
def leadtime_crossdock_calc(slt, wlt, dow, freq):
temp_lt = [0, 0, 0, 0, 0, 0, 0]
remaining = []
for i in range(0, 7):
remaining.append((dow[i:] + dow[:i]).index(1))
for i in range(7):
if freq[i] == 1:
supplier_lt = int(slt[i])
warehouse_lt = int(wlt[(i + supplier_lt) % 7])
waiting = int(remaining[(i + supplier_lt + warehouse_lt) % 7])
temp_lt[i] = supplier_lt + warehouse_lt + waiting
for i in range(7):
if temp_lt[i] == 0:
temp_lt[i] = next((value for index, value in enumerate(temp_lt[i:] + temp_lt[:i]) if value), None)
return ''.join(str(x) for x in temp_lt)
它變成了下面的例子;
leadtime_crossdock_calc([0,2,0,2,0,3,0],[1,1,1,1,1,1,1],[0,0,1,0,1,0,1],[0,1,0,1,0,1,0])
'3333443'
問題是,我有一個如下所示的火花數據框;
Product Store slt wlt dow freq
A B [0,2,0,2,0,3,0] [1,1,1,1,1,1,1] [0,0,1,0,1,0,1] [0,1,0,1,0,1,0]
我想使用上述方法為數據框中的每個新行創建一個新列;
Product Store slt wlt dow freq result
A B [0,2,0,2,0,3,0] [1,1,1,1,1,1,1] [0,0,1,0,1,0,1] [0,1,0,1,0,1,0] [3,3,3,3,4,4,3]
你能幫我解決這個問題嗎? 我無法應用火花數據幀的方法。
您可以使用User Defined Functions 或 UDF First 在 spark 上注冊您的 UDF,指定返回函數類型。 你可以使用這樣的東西:
from pyspark.sql.types import StringType, col
leadtime_udf = spark.udf.register("leadtime_udf", leadtime_crossdock_calc, StringType())
然后,您可以將該 UDF 應用於您的 DataFrame(或也在 Spark SQL 中)
df.select("*", leadtime_udf(col(slt), ... , col(freq)))
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.