我正在嘗試根據串列和概率使用隨機字串值填充 Spark 列。從我讀過的內容來看,似乎需要一個嵌套函式。我正在嘗試下面的方法,它可以正常作業,除了它為每一行回傳相同的采樣值。例如,它都是 A 或 B 或 C。該函式必須在其狀態下被腌制。如何修復生成隨機抽獎?
def sim_strings(lst_choices, lst_probs):
import random
str_sampled = random.choices(lst_choices, weights = lst_probs)[0]
def f(x):
return(str_sampled)
return (F.udf(f))
lst_choices_ = ['A', 'B', 'C']
lst_probs_ = [0.5, 0.45, 0.05]
df.withColumn('newcol', sim_strings(lst_choices = lst_choices_, lst_probs = lst_probs_)(F.col('existingcol'))).select('newcol').show(100)
uj5u.com熱心網友回復:
Imo 現在你只呼叫 random.choices 一次,然后你在你的 f 函式中回傳它。
不確定這是否是您想要的,但我嘗試了類似的方法,現在每一行都呼叫了 random.choices
def sim_strings(lst_choices, lst_probs):
import random
def f(x):
return(random.choices(lst_choices, weights = lst_probs)[0])
return (F.udf(f))
看起來結果符合預期:
------
|newcol|
------
| B|
| B|
| A|
| A|
| B|
| B|
| A|
| A|
| A|
| C|
| A|
| A|
| B|
| B|
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537489.html
