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

2024-09-27 17:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

对于表1中的每一行,我都在尝试统计表2中的行,并根据表1中的值满足条件

表1中的年龄应介于表2的起始年龄和结束年龄之间,或等于起始年龄和结束年龄

是否可以使用udf和WITH列进行此操作?我尝试了几种方法,比如使用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


Tags: 方法agereturndefwithcounterwhere年龄
2条回答

如果要在脚本中使用自定义项,必须首先向spark注册它

使用这行代码有助于修复错误:

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

看看这个。您可以使用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|
    # +   +  -+

相关问题 更多 >

    热门问题