Morit
Morit

Reputation: 201

How to get split values instead of bucket index in pyspark.bucketizer

I'm trying to get the splits values as a result when using bucketizer in pyspark. Currently the result contains the bucket's index:

data = [(0, -1.0), (1, 0.0), (2, 0.5), (3, 1.0), (4, 10.0),(5, 25.0),(6, 100.0),(7, 300.0),(8,float("nan"))]
df = spark.createDataFrame(data, ["id", "value"])
splits = [-float("inf"),0,0.001, 1, 5,10, 20, 30, 40, 50, 60, 70, 80, 90, 100, float("inf")]
result_bucketizer = Bucketizer(splits=splits, inputCol="value",outputCol="result").setHandleInvalid("keep").transform(df)
result_bucketizer.show()

The result is:

+---+-----+------+
| id|value|result|
+---+-----+------+
|  0| -1.0|   0.0|
|  1|  0.0|   1.0|
|  2|  0.5|   2.0|
|  3|  1.0|   3.0|
|  4| 10.0|   5.0|
|  5| 25.0|   6.0|
|  6|100.0|  14.0|
|  7|300.0|  14.0|
|  8|  NaN|  15.0|
+---+-----+------+

I want the result to be:

+---+-----+------+
| id|value|result|
+---+-----+------+
|  0| -1.0|  -inf|
|  1|  0.0|   0.0|
|  2|  0.5| 0.001|
|  3|  1.0|   1.0|
|  4| 10.0|  10.0|
|  5| 25.0|  20.0|
|  6|100.0| 100.0|
|  7|300.0| 100.0|
|  8|  NaN|   NaN|
+---+-----+------+ 

Upvotes: 2

Views: 5837

Answers (1)

Daniel Fernandez
Daniel Fernandez

Reputation: 71

This is the way I did it.

First I created the dataframe.

from pyspark.ml.feature import Bucketizer
from pyspark.sql.types import StringType

data = [(0, -1.0), (1, 0.0), (2, 0.5), (3, 1.0), (4, 10.0),(5, 25.0),(6, 100.0),(7, 300.0),(8,float("nan"))]
df = spark.createDataFrame(data, ["id", "value"])
splits = [-float("inf"),0,0.001, 1, 5,10, 20, 30, 40, 50, 60, 70, 80, 90, 100, float("inf")]
# here I created a dictionary with {index: name of split}
splits_dict = {i:splits[i] for i in range(len(splits))}

Then I created the bucketizer as a separate variable.

# create bucketizer
bucketizer = Bucketizer(splits=splits, inputCol="value",outputCol="result")
# bucketed dataframe
bucketed = bucketizer.setHandleInvalid('skip').transform(df)

To get the labels I just applied the replace function using the dict we defined earlier.

bucketed = bucketed.replace(to_replace=splits_dict, subset=['result'])
bucketed.show()

output:

+---+-----+---------+
| id|value|   result|
+---+-----+---------+
|  0| -1.0|-Infinity|
|  1|  0.0|      0.0|
|  2|  0.5|    0.001|
|  3|  1.0|      1.0|
|  4| 10.0|     10.0|
|  5| 25.0|     20.0|
|  6|100.0|    100.0|
|  7|300.0|    100.0|
+---+-----+---------+

Upvotes: 4

Related Questions