I have a PySpark DataFrame df which has a numerical column (with NaNs)
+-------+
|numbers|
+-------+
| 142.56|
| |
|2023.33|
| 477.76|
| 175.52|
|1737.45|
| 520.72|
| 641.2|
| 79.3|
| 138.43|
+-------+
I want to create a new column which defines some bins, e.g. 0, (0, 500], (500, 1000], (1000, inf)
Is there a way to accomplish this using a function like pandas.cut? At the moment the way I do this with PySpark is by defining an udf function as follows, but this approach has the disadvantage to be tedious and non-parametric
from pyspark.sql import functions as F
from pyspark.sql.types import *
def func(numbers):
if numbers==0:
return '0'
elif numbers>0 and numbers<=500:
return '(0, 500]'
elif numbers>500 and numbers<=1000:
return '(500, 1000]'
elif numbers>500:
return '(500, inf)'
else return 'Other'
func_udf = F.udf(func, StringType())
df.withColumn('numbers_bin', func_udf(df['numbers']))
If df was a Pandas DataFrame, I would have used this approach:
df['numbers_bin'] = pd.cut(
df['numbers'],
np.concatenate((-np.inf, [0, 500, 1000], np.inf), axis=None))
Which is way more cleaner and modular