I have min 12 periods in list, these are not fixed might have more based on the selected product. Also, I have a dict which has period as key and products as list of values.
{
"20191": ["prod1","prod2","prod3"],
"20192": ["prod2","prod3"],
"20193": ["prod2"]
}
II need to select the data based on period and compute the sum of the respective period, amount.
sample_data
| period | product | amount |
|---|---|---|
| 20191 | prod1 | 30 |
| 20192 | prod1 | 30 |
| 20191 | prod2 | 20 |
| 20191 | prod3 | 60 |
| 20193 | prod1 | 30 |
| 20193 | prod2 | 30 |
output
| period | product | amount |
|---|---|---|
| 20191 | prod1 | 110 |
| 20192 | 0 | |
| 20193 | prod3 | 30 |
Basically, for each of the period, select only those products from the dict, and sum it up.
My code which is taking lot of time:
list_series = []
df = spark.read.csv(path,header=True)
periods = df.select("period").distinct().collect()
for period in periods:
df1 = df.filter(f"period = {period}").filter(F.col("product").isin(dict["period"]).groupBy("priod","product").agg(F.sum("Amount").alias("Amount")
list_series.append(df1)
dataframe = reduce(DataFrame.unionAll,list_series)
Is there any way, I can modify and increase the performance?