pandas groupby.apply to pyspark

2024-10-03 02:45:14 发布

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

我有以下自定义函数在pandas数据帧中进行聚合,我想在pyspark中做同样的事情:

def custom_aggregation_pyspark(x,queries):
    names={}
    for k, v in regles_calcul.items():
        plus = x.query(v["plus_credit"])['OBNETCRE'].sum() + x.query(v["plus_debit"])['OBNETDEB'].sum()
        minus = x.query(v["minus_credit"])['OBNETCRE'].sum() + x.query(v["minus_debit"])['OBNETDEB'].sum()  

     

        names[k]= plus-minus
    return pd.Series(names, index=list(names.keys()))


df = df.groupby(['LBUDG']).apply(custom_aggregation_pandas, queries ).sum()

WARE查询是一个类似查询的字典

{'first_queries': {   
    'plus_credit': "classe_compte_rg2 in ('237', '238')",
    'plus_debit': "classe_compte_rg2 in ('237', '238')", 
    'minus_credit': "classe_compte_rg2 in ('237', '238')", 
    'minus_debit': "classe_compte_rg1 in ('20', '21', '23')"
     }
}

因此,我用pyspark'sql'替换了pandas“query”

def custom_aggregation_pyspark(x,queries):
    x.createOrReplaceTempView("df")
    names={}
    for k , v in queries.items():
        plus = spark.sql("SELECT * FROM df WHERE "+ v["plus_credit"]).select('OBNETCRE').groupby('OBNETCRE').sum().collect() + spark.sql("SELECT * FROM df WHERE "+ v["plus_debit"]).select('OBNETDEB').groupby('OBNETDEB').sum().collect() 
        minus= spark.sql("SELECT * FROM df WHERE "+ v["minus_credit"]).select('OBNETCRE').groupby('OBNETCRE').sum().collect() + spark.sql("SELECT * FROM df WHERE "+ v["minus_debit"]).select('OBNETDEB').groupby('OBNETDEB').sum().collect() 
        names[k]= plus-minus
    return pd.Series(names, index=list(names.keys()))

df.groupby("LBUDG").agg(custom_aggregation_pyspark(df,queries))

我肯定是走错了方向,因为上面的代码不起作用,你能告诉我应该去哪里看吗

所需的输出是一个按LBUDG(字符串)分组的表,其他列使用自定义聚合函数

编辑数据帧示例:

^{tb1}$

预期产出:

^{tb2}$

其中agg1(例如)对应于OBNETCRE - OBNETDEB的和,其中classe_compte_rg1有值,为10或11


Tags: indfnamesplusquerypysparksumdebit
1条回答
网友
1楼 · 发布于 2024-10-03 02:45:14

您可以使用epxr来计算queriesdict中传递的条件,并使用条件聚合来计算总和。下面是一个与您在《熊猫》中给出的示例相同的示例:

from pyspark.sql import functions as F


def custom_aggregation_pyspark(df, regles_calcul):
    df1 = df.groupBy("LBUDG") \
        .agg(
        *[
            ((F.sum(F.when(F.expr(v["plus_credit"]), F.col("OBNETCRE")).otherwise(0)) +
              F.sum(F.when(F.expr(v["plus_debit"]), F.col("OBNETDEB")).otherwise(0))) -
             (F.sum(F.when(F.expr(v["minus_credit"]), F.col("OBNETCRE")).otherwise(0)) +
              F.sum(F.when(F.expr(v["minus_debit"]), F.col("OBNETDEB")).otherwise(0)))
             ).alias(k)

            for k, v in regles_calcul.items()
        ]
    )

    return df1


df = custom_aggregation_pyspark(df, queries)

相关问题 更多 >