I have a dataframe as below. Trying to figure out how to calculate the percentage of each colour per product, and generate something like the expected output. I tried to use a window w= Window.partitionBy["prod_name","colour"] and do a count df.withColumn("cnt", F.count("colour").over("w"))but that's far from correct as that only count the number of the "colour" column. Could someone please help? Many thanks.
Input:
prod_name | colour
---------------
A | blue
A | blue
A | yellow
B | green
B | blue
C | red
Output:
prod_name | colour | percentage
----------------------
A | blue. | 0.67. ---- as blue account for 2/3 of product A
A | yellow.| 0.33 --- yellow account for 1/3 of product A
B | green |. 0.5 --- green account for 1/2 of product B
B | blue. | 0.5 --- blue account for 1/2 of product B
C | red. | 1 --- red account for 100% of product C