I have the following python dictionary:
ranges = {
(0, 10): '0 - 10',
(10, 100): '10 - 100',
(100, float('inf')): '100+'
}
And the following df:
| Id | Value |
|---|---|
| 001 | 9 |
| 002 | 10 |
| 003 | 300 |
I would like to add a column that returns the dictionary's value if the "Value" column is between (exclusive) the two numbers in the dictionary's key.
So resulting df should look like this:
| Id | Value | Range |
|---|---|---|
| 001 | 9 | 0 - 10 |
| 002 | 10 | 10 - 100 |
| 003 | 300 | 100+ |
I know I can use withColumn and when, e.g.:
df.withColumn(
'Range',
.when((col('Value') >= lit(0)) & (col('Value') < lit(10)), '0 - 10')
)
and so on, but it would be inefficient if I have 100s of key-value pairs or wanted to test with different numbers in the keys.
Hopefully this makes sense. I would appreciate any and all inputs. Thank you so much in advance.