Function 如何在Pyspark中传递动态参数以过滤函数?

Function 如何在Pyspark中传递动态参数以过滤函数?,function,filter,pyspark,parameter-passing,Function,Filter,Pyspark,Parameter Passing,大家好 我有几个查询需要开发,我想用一个函数自动化整个过程,唯一的问题是整个结构实际上是相同的,有两件事情会发生变化,第一件是过滤器,第二件是创建Group_Service列 例如,对于第一个查询,我在服务列上有一个过滤器,其中f.col(“服务”)。例如(“%New Bank ROME%”)&组服务列的创建如下: .withColumn('group_service',f.lit('ROME Services”).cast(“字符串”)) 对于第二个查询,我在服务列上有一个过滤器,其中f.co

大家好

我有几个查询需要开发,我想用一个函数自动化整个过程,唯一的问题是整个结构实际上是相同的,有两件事情会发生变化,第一件是过滤器,第二件是创建Group_Service

例如,对于第一个查询,我在服务列上有一个过滤器,其中f.col(“服务”)。例如(“%New Bank ROME%”)&组服务列的创建如下: .withColumn('group_service',f.lit('ROME Services”).cast(“字符串”))

对于第二个查询,我在服务列上有一个过滤器,其中f.col(“服务”)。如(“%New Bank BERLIN%”)&集团服务列的创建如下: .withColumn('group_service',f.lit('BERLIN Services”).cast('string'))

在某些情况下,过滤器和组服务列甚至不存在,因此查询将不包括这两个

这是我的密码:

def Query(df):
    df_1 = df.filter(df.customer.like('IT - ROME%') 
                & (f.col("day") > datetime(2017, 1, 1, 0, 0, 0))
        & (df.service.like('% New Bank ROME%')))\
                .select("day" , "customer" , "availability" ,  f.month(f.col("day")).cast("string").alias("month"))\
                .select("day" , "month" , "availability"  , "customer" ,  f.year(f.col("day")).cast("string").alias("year"))\
                .withColumn('group_service', f.lit("ROME Services").cast("string"))\
                .withColumn("year_month_s", f.when((f.col("month") == "10") | (f.col("month") == "11") | (f.col("month") == "12") , 
                f.concat(f.col("year"), f.lit(" "),f.col("month")))
                .otherwise( f.concat(f.col("year"), f.lit(" 0"),f.col("month")))
                ).distinct()\
                .withColumn("customer", f.when(f.col('customer').like('IT - ROME%')
                , 'IT - ROME - BANK'))\

因此,我想知道如何使用附加的动态参数“自动化”整个过程,非常感谢您的帮助,谢谢您只需将位置替换为格式字符串:

def Query(df, location, service):
    df_1 = df.filter(df.customer.like(f'IT - {location}%') 
                     & (f.col("day") > datetime(2017, 1, 1, 0, 0, 0))
    if service:
        df_1 = df_1 & (df.service.like(f'% New Bank {location}%')))\
                .select("day" , "customer" , "availability" ,  f.month(f.col("day")).cast("string").alias("month"))\
                .select("day" , "month" , "availability"  , "customer" ,  f.year(f.col("day")).cast("string").alias("year"))\
                .withColumn('group_service', f.lit(f"{location} Services").cast("string"))\
                .withColumn("year_month_s", f.when((f.col("month") == "10") | (f.col("month") == "11") | (f.col("month") == "12") , 
                f.concat(f.col("year"), f.lit(" "),f.col("month")))
                .otherwise( f.concat(f.col("year"), f.lit(" 0"),f.col("month")))
                ).distinct()\
                .withColumn("customer", f.when(f.col('customer').like(f'IT - {location}%')
                , f'IT - {location} - BANK'))

谢谢,但是如果我的查询没有服务的条件,它还会工作吗,再次感谢你