PySpark:对于每一行,根据条件计数另一个表

时间:2020-07-27 16:53:46

标签: python apache-spark pyspark apache-spark-sql databricks

对于表1中的每一行,我试图根据表1中的值对表2中满足条件的行进行计数。

表1中的年龄应介于表2的StartAge和EndAge之间,或者等于StartAge和EndAge。

使用udf和withColumn可以实现吗?我尝试了几种方法来做到这一点,例如将withColumn和withColumn与UDF一起使用,但是两种方法都失败了。

def counter(a):
    return table2.where((table2.StartAge <= a) & (table2.EndAge >=a)).count()

counter_udf = udf(lambda age: counter(age), IntegerType())

table1 = table1.withColumn('Count', counter_udf('Age ID'))

这有意义吗? 谢谢。

示例输入和输出:

enter image description here

2 个答案:

答案 0 :(得分:1)

检查一下。您可以使用spark-sql来实现。

    from pyspark.sql import SparkSession

    spark = SparkSession.builder \
        .appName('SO')\
        .getOrCreate()

    sc= spark.sparkContext

    df = sc.parallelize([([3]), ([4]), ([5])]).toDF(["age"])

    df1 = spark.createDataFrame([(0, 10), (7, 15), (5, 10), (3, 20), (5, 35), (4, 5),]
                           , ['age_start', 'age_end'])

    df.createTempView("table1")

    df1.createTempView("table2")



    spark.sql('select  t1.age as age_id, count(*) as count from table1 t1 join table2  t2 on  t1.age >=t2.age_start and t1.age<=t2.age_end group by t1.age order by count').show()

    # +------+-----+
    # |age_id|count|
    # +------+-----+
    # |     3|    2|
    # |     4|    3|
    # |     5|    5|
    # +------+-----+

答案 1 :(得分:-1)

如果要在脚本中使用UDF,则必须先在spark中注册它。

使用以下代码行应有助于纠正错误:

_ = spark.udf.register("counter_udf", counter_udf)