我有一个PySpark数据框,其中包含一个ID,然后包含几个要为其计算95%点的变量。
printSchema()的一部分:
root
|-- ID: string (nullable = true)
|-- MOU_G_EDUCATION_ADULT: double (nullable = false)
|-- MOU_G_EDUCATION_KIDS: double (nullable = false)
我找到了How to derive Percentile using Spark Data frame and GroupBy in python,但这失败并显示一条错误消息:
perc95_udf = udf(lambda x: x.quantile(.95))
fanscores = genres.withColumn("P95_MOU_G_EDUCATION_ADULT", perc95_udf('MOU_G_EDUCATION_ADULT')) \
.withColumn("P95_MOU_G_EDUCATION_KIDS", perc95_udf('MOU_G_EDUCATION_KIDS'))
fanscores.take(2)
AttributeError:“浮动”对象没有属性“分位数”
我已经尝试过的其他UDF试验:
def percentile(quantiel,kolom):
x=np.array(kolom)
perc=np.percentile(x, quantiel)
return perc
percentile_udf = udf(percentile, LongType())
fanscores = genres.withColumn("P95_MOU_G_EDUCATION_ADULT", percentile_udf(quantiel=95, kolom=genres.MOU_G_EDUCATION_ADULT)) \
.withColumn("P95_MOU_G_EDUCATION_KIDS", percentile_udf(quantiel=95, kolom=genres.MOU_G_EDUCATION_KIDS))
fanscores.take(2)
给出错误:“ TypeError:wrapper()得到了意外的关键字参数'quantiel'”
我的最终审判:
import numpy as np
def percentile(quantiel):
return udf(lambda kolom: np.percentile(np.array(kolom), quantiel))
fanscores = genres.withColumn("P95_MOU_G_EDUCATION_ADULT", percentile(quantiel=95)(genres.MOU_G_EDUCATION_ADULT)) \
.withColumn("P95_MOU_G_EDUCATION_KIDS", percentile(quantiel=95) (genres.MOU_G_EDUCATION_KIDS))
fanscores.take(2)
给出错误:
PickleException:预期用于构造ClassDict的零参数(对于numpy.dtype)
我该如何解决?
答案 0 :(得分:1)
df.selectExpr('percentile(MOU_G_EDUCATION_ADULT, 0.95)').show()
对于大型数据集,请考虑使用percentile_approx()