Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Apache spark 使用groupby聚合另一列上具有条件的行上的列_Apache Spark_Pyspark_Group By_Apache Spark Sql_Aggregate Functions - Fatal编程技术网

Apache spark 使用groupby聚合另一列上具有条件的行上的列

Apache spark 使用groupby聚合另一列上具有条件的行上的列,apache-spark,pyspark,group-by,apache-spark-sql,aggregate-functions,Apache Spark,Pyspark,Group By,Apache Spark Sql,Aggregate Functions,假设我有以下Pyspark数据帧: Country Direction Quantity Price Belgium In 5 10 Belgium Out 2 8 Belgium Out 3 9 France In 2 3 France Out 3

假设我有以下Pyspark数据帧:

 Country    Direction    Quantity     Price
 Belgium    In           5            10
 Belgium    Out          2            8
 Belgium    Out          3            9
 France     In           2            3
 France     Out          3            2
 France     Out          4            3
 
是否可以按此数据帧按列“国家”分组,将“价格”列的合计平均值作为正常值,但对“数量”列使用函数“第一”,仅在“方向”列为“输出”时才对行使用函数“第一”? 我想应该是这样的:

df.groupby("Country").agg(F.mean('Price'), F.first(F.col('Quantity').filter(F.col('Direction') == "Out")))

您可以为
方向屏蔽
数量
out'
并首先使用
ignoreNulls执行
操作

df.groupby("Country").agg(
    F.mean('Price'),
    F.first(
        F.when(
            F.col('Direction') == "Out",
            F.col('Quantity')
        ),
        ignoreNulls=True
    )
)