Context
A dataframe should have the category column, which is based on a set of fixed rules. The set of rules becomes quite large.
Question
Is there a way to use a list of tuples (see example below) to dynamically chain the when conditions to achieve the same result as hard coded solution at the bottom.
# Potential list of rule definitions
category_rules = [
('A', 8, 'small'),
('A', 30, 'large'),
('B', 5, 'small'),
# Group, size smaller value --> Category
# and so on ... e.g.,
]
Example
Here is a toy example for reproducibility. A dataframe consisting of groups and ids should have the column category added, which depends on the content of the group column. The list of rules is shown in the section above.
data = [('A', '45345', 5), ('C', '55345', 5), ('A', '35345', 10), ('B', '65345', 4)]
df = spark.createDataFrame(data, ['group', 'id', 'size'])
+-----+-----+-----+
|group| id| size|
+-----+-----+-----+
| A|45345| 5|
| C|55345| 5|
| A|35345| 10|
| B|65345| 4|
+-----+-----+-----+
Hard coded solution
df = df.withColumn(
'category',
F.when(
(F.col('group') == 'A')
& (F.col('size') < 8),
F.lit('small')
).when(
(F.col('group') == 'A')
& (F.col('size') < 30),
F.lit('large')
).when(
(F.col('group') == 'B')
& (F.col('size') < 5),
F.lit('small')
).otherwise(
F.lit('unkown')
)
)
+-----+-----+----+--------+
|group| id|size|category|
+-----+-----+----+--------+
| A|45345| 5| small|
| C|55345| 5| unkown|
| A|35345| 10| large|
| B|65345| 4| small|
+-----+-----+----+--------+
[Edit 1] Add more complex conditions to explain why chaining is needed.