I have a spark dataframe where one column is an array of structs.
df = spark.createDataFrame([(1, [{"col1": 10, "col2": 0.8, "col3": 0.1}, {"col1": 9, "col2": 1.8, "col3":0.0}, {"col1": 8, "col2": 1.9, "col3": None}])], ['rowNum', 'vals'])
I am trying to create an aggregate function that sums all of the col2s and divides it by all of the col1s you can ignore col3. I know how to create an aggregate function if I was just summing one of the columns (using higher order functions in pyspark 2.4+), but is it possible to sum 2 items at the same time, or do I have to do it as 2 separate steps.
If I have to do it as 2 separate steps, then I can do:
df = df.withColumn("sum", F.aggregate("vals", F.lit(0.0), lambda x, y: x + y.col2)) \
.withColumn("denom", F.aggregate("vals", F.lit(0.0), lambda x, y: x + y.col1)) \
.withColumn("output", F.col('sum')/F.col('denom'))
I was wondering if there is a higher order function that does this in a cleaner way/in 1 step? Many thanks.