sap*_*top 1 arrays random sample pyspark
我在 Pyspark 数据框中有一列,其结构类似于
Column1
[a,b,c,d,e]
[c,b,d,f,g,h,i,p,l,m]
Run Code Online (Sandbox Code Playgroud)
我想返回另一列,随机选择每行中的每个数组,函数中指定的数量。
所以就像data.withColumn("sample", SOME_FUNCTION("column1", 5))返回:
sample
[a,b,c,d,e]
[c,b,h,i,p]
Run Code Online (Sandbox Code Playgroud)
希望避免使用python UDF,感觉应该有一个可用的功能??
这有效:
import random
def random_sample(population):
return(random.sample(population, 5))
udf_random = F.udf(random_sample, T.ArrayType(T.StringType()))
df.withColumn("sample", udf_random("column1")).show()
Run Code Online (Sandbox Code Playgroud)
但正如我所说,最好避免使用 UDF。
对于 spark 2.4+,使用shuffle和slice:
df = spark.createDataFrame([(list('abcde'),),(list('cbdfghiplm'),)],['column1'])
df.selectExpr('slice(shuffle(column1),1,5)').show()
+-----------------------------+
|slice(shuffle(column1), 1, 5)|
+-----------------------------+
| [b, a, e, d, c]|
| [h, f, d, l, m]|
+-----------------------------+
Run Code Online (Sandbox Code Playgroud)