python - 如何在 pyspark.bucketizer 中获取拆分值而不是存储桶索引
问题描述
在 pyspark 中使用 bucketizer 时,我试图获取拆分值。当前结果包含存储桶的索引:
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()
结果是:
+---+-----+------+
| 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|
+---+-----+------+
我希望结果是:
+---+-----+------+
| 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|
+---+-----+------+
解决方案
我就是这样做的。
首先,我创建了数据框。
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))}
然后我将分桶器创建为一个单独的变量。
# create bucketizer
bucketizer = Bucketizer(splits=splits, inputCol="value",outputCol="result")
# bucketed dataframe
bucketed = bucketizer.setHandleInvalid('skip').transform(df)
为了获得标签,我刚刚使用我们之前定义的 dict 应用了 replace 函数。
bucketed = bucketed.replace(to_replace=splits_dict, subset=['result'])
bucketed.show()
输出:
+---+-----+---------+
| 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|
+---+-----+---------+
推荐阅读
- c# - Windows UWP BluetoothLEDevice 重新连接
- python - 使用 python 异步运行 docker 容器
- php - 在 CURL 请求和重定向 php 之后登录
- talend - 使用 shell 可执行文件运行特定的 talend 组件
- javascript - React - 无法从 Redux 获取数据
- php - php artisan 在加载另一个页面或提交表单时服务缓慢
- javascript - 在 react-native 移动应用程序中编写环境条件的最佳方法?
- android - 分发适用于 android wear 的 apk
- python-2.7 - 传单 - 平铺地图移动
- sql - delphi -> sql server 查询返回空字符串,但长度正确