PySpark - Pass list as parameter to UDF

前端 未结 3 514
挽巷
挽巷 2020-12-13 21:27

I need to pass a list into a UDF, the list will determine the score/category of the distance. For now, I am hard coding all distances to be the 4th score.

a=         


        
相关标签:
3条回答
  • 2020-12-13 21:45

    Hope this helps!

    from pyspark.sql.functions import udf, col
    
    #sample data
    a= sqlContext.createDataFrame([("A", 20), ("B", 30), ("D", 80)],["Letter", "distances"])
    label_list = ["Great", "Good", "OK", "Please Move", "Dead"]
    
    def cate(label, feature_list):
        if feature_list == 0:
            return label[4]
        else:  #you may need to add 'else' condition as well otherwise 'null' will be added in this case
            return 'I am not sure!'
    
    def udf_score(label_list):
        return udf(lambda l: cate(l, label_list))
    a.withColumn("category", udf_score(label_list)(col("distances"))).show()
    

    Output is:

    +------+---------+--------------+
    |Letter|distances|      category|
    +------+---------+--------------+
    |     A|       20|I am not sure!|
    |     B|       30|I am not sure!|
    |     D|       80|I am not sure!|
    +------+---------+--------------+
    
    0 讨论(0)
  • 2020-12-13 21:49

    I think this may help by passing list as a default value of a variable

    from pyspark.sql.functions import udf, col
    
    #sample data
    a= sqlContext.createDataFrame([("A", 20), ("B", 30), ("D", 80),("E",0)],["Letter", "distances"])
    label_list = ["Great", "Good", "OK", "Please Move", "Dead"]
    
    #Passing List as Default value to a variable
    def cate( feature_list,label=label_list):
        if feature_list == 0:
            return label[4]
        else:  #you may need to add 'else' condition as well otherwise 'null' will be added in this case
            return 'I am not sure!'
    
    udfcate = udf(cate, StringType())
    
    a.withColumn("category", udfcate("distances")).show()
    

    Output:

    +------+---------+--------------+
    |Letter|distances|      category|
    +------+---------+--------------+
    |     A|       20|I am not sure!|
    |     B|       30|I am not sure!|
    |     D|       80|I am not sure!|
    |     E|        0|          Dead|
    +------+---------+--------------+
    
    0 讨论(0)
  • 2020-12-13 21:53

    Try currying the function, so that the only argument in the DataFrame call is the name of the column on which you want the function to act:

    udf_score=udf(lambda x: cate(label_list,x), StringType())
    a.withColumn("category", udf_score("distances")).show(10)
    
    0 讨论(0)
提交回复
热议问题