scala - Spark(Scala)udf修改数据框列中的地图
问题描述
我有一个看起来像这样的数据框。该tfs
列是 String 到 Long 的映射,并且weights
是浮点数
+----------+---+------------------------+------------------+
|term |df |tfs |weight |
+----------+---+------------------------+------------------+
|keyword1 |2 |{2.txt -> 2, 1.txt -> 2}|1.3 |
|keyword2 |1 |{2.txt -> 1} |0.6931471805599453|
|keyword3 |2 |{2.txt -> 1, 1.txt -> 2}|0.52343473 |
+----------+---+------------------------+------------------+
我想通过将tfs
地图中的每个值乘以其各自的权重来组合最后两列,以获得类似
+----------+---+------------------------------------------+
|term |df |weighted-tfs |
+----------+---+------------------------------------------+
|keyword1 |2 |{2.txt -> 2.6, 1.txt -> 2.6} |
|keyword2 |1 |{2.txt -> 0.6931471805599453} |
|keyword3 |2 |{2.txt -> 0.52343473, 1.txt -> 1,04686946}|
+----------+---+------------------------------------------+
我的猜测是为此编写一个 udf 会很简单,但我在 Spark 和 Scala 方面都很有经验,所以我不知道该怎么做。
解决方案
使用map_from_arrays
, map_keys
&map_values
函数。
试试下面的代码。
val finalDF = df
.withColumn(
"weighted-tfs",
map_from_arrays(
map_keys($"tfs"),
expr("transform(map_values(tfs),i -> i * weight)")
)
)
输出
finalDF.show(false)
+--------+---+------------------------+------------------+------------------------------------------+
|term |df |tfs |weight |product |
+--------+---+------------------------+------------------+------------------------------------------+
|keyword1|2 |[2.txt -> 2, 1.txt -> 2]|1.3 |[2.txt -> 2.6, 1.txt -> 2.6] |
|keyword2|1 |[2.txt -> 1] |0.6931471805599453|[2.txt -> 0.6931471805599453] |
|keyword3|2 |[2.txt -> 1, 1.txt -> 2]|0.52343473 |[2.txt -> 0.52343473, 1.txt -> 1.04686946]|
+--------+---+------------------------+------------------+------------------------------------------+
推荐阅读
- javascript - 获取 JSON 不在站点中但在 localhost 中工作
- python - 按 True 序列分组
- python - 如何修复元组索引超出范围
- android - 如何从函数内部更新通知显示
- angular - 如何使用 WebStorm 中的“创建方法”功能启用 HTML 中的错误突出显示?
- php - Woocommerce 上门付款,从正在处理到等待状态
- javascript - 如何在有限的函数中执行这个结果
- r - 使用不同的组规则自动执行 group_by 函数
- java - Java一次从一组中获取n个项目
- php - 如何在 Laravel 8 中每次在同一个 cookie 中插入多个值