来自 ArrayType Pyspark 列的随机样本
Random sample from column of ArrayType Pyspark
我在 Pyspark 数据框中有一列,其结构类似于
Column1
[a,b,c,d,e]
[c,b,d,f,g,h,i,p,l,m]
我想 return 另一列随机选择每行中的每个数组,数量在函数中指定。
所以像 data.withColumn("sample", SOME_FUNCTION("column1", 5))
returning:
sample
[a,b,c,d,e]
[c,b,h,i,p]
希望避免 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()
但正如我所说,最好避免使用 UDF。
对于 spark 2.4+,使用 shuffle
and 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]|
+-----------------------------+
我在 Pyspark 数据框中有一列,其结构类似于
Column1
[a,b,c,d,e]
[c,b,d,f,g,h,i,p,l,m]
我想 return 另一列随机选择每行中的每个数组,数量在函数中指定。
所以像 data.withColumn("sample", SOME_FUNCTION("column1", 5))
returning:
sample
[a,b,c,d,e]
[c,b,h,i,p]
希望避免 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()
但正如我所说,最好避免使用 UDF。
对于 spark 2.4+,使用 shuffle
and 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]|
+-----------------------------+