简体   繁体   中英

Pandas to pyspark cumprod function

I am trying to convert below pandas code to pyspark

Python Pandas code:

df = spark.createDataFrame([(1, 1,0.9), (1, 2,0.13), (1, 3,0.5), (1, 4,1.0), (1, 5,0.6)], ['col1', 'col2','col3'])
pandas_df = df.toPandas()

pandas_df['col4'] = (pandas_df.groupby(['col1','col2'])['col3'].apply(lambda x: (1 - x).cumprod()))
pandas_df

and the result is below:

   col1  col2  col3  col4
0     1     1  0.90  0.10
1     1     2  0.13  0.87
2     1     3  0.50  0.50
3     1     4  1.00  0.00
4     1     5  0.60  0.40

and converted spark code:

from pyspark.sql import functions as F, Window, types
from functools import reduce
from operator import mul

df = spark.createDataFrame([(1, 1,0.9), (1, 2,0.13), (1, 3,0.5), (1, 4,1.0), (1, 5,0.6)], ['col1', 'col2','col3'])
partition_column = ['col1','col2']
window = Window.partitionBy(partition_column)
expr = 1.0 - F.col('col3')
mul_udf = F.udf(lambda x: reduce(mul, x), types.DoubleType())
df = df.withColumn('col4', mul_udf(F.collect_list(expr).over(window)))
df.orderBy('col2').show()

and its output

+----+----+----+-------------------+
|col1|col2|col3|               col4|
+----+----+----+-------------------+
|   1|   1| 0.9|0.09999999999999998|
|   1|   2|0.13|               0.87|
|   1|   3| 0.5|                0.5|
|   1|   4| 1.0|                0.0|
|   1|   5| 0.6|                0.4|
+----+----+----+-------------------+

I don't completely understand how pandas work, can someone help me validate whether the above conversion is correct and also I am using UDF, which will reduce the performance, is there any distributed function available in pyspark that will do cumprod() ?

thanks in advance

Since product of positive numbers can be expressed with log and exp functions ( a*b*c = exp(log(a) + log(b) + log(c)) ), you can calculate cumulative product using only Spark built-in functions:

df.groupBy("col1", "col2") \
  .agg(max(col("col3")).alias("col3"),
       coalesce(exp(sum(log(lit(1) - col("col3")))), lit(0)).alias("col4")
  )\
  .orderBy(col("col2"))\
  .show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM