python - 用于聚合字典的 ReduceByKey 方法
问题描述
我有一个 spark 方法,我正在运行一个flatMap
返回元组列表的函数。元组中的键值是 a Timestamp
,值是 a dict
。
[(Timestamp('2000-01-01 00:00:00'),
{'id': '1', 'val': '200M', 'date':Timestamp('2000-01-01 00:00:00')}),
(Timestamp('2000-01-01 00:00:00'),
{'id': '2', 'val': '10M', 'date':Timestamp('2000-01-01 00:00:00')}),
(Timestamp('2000-01-01 00:00:00'),
{'id': '3', 'val': '30M', 'date':Timestamp('2000-01-01 00:00:00')}),
(Timestamp('2000-01-02 00:00:00'),
{'id': '15', 'val': '120M', 'date':Timestamp('2000-01-02 00:00:00')}),
(Timestamp('2000-01-02 00:00:00'),
{'id': '3', 'val': '35M', 'date':Timestamp('2000-01-02 00:00:00')}),
(Timestamp('2000-01-02 00:00:00'),
{'id': '4', 'val': '56M', 'date':Timestamp('2000-01-02 00:00:00')}),
(Timestamp('2000-01-03 00:00:00'),
{'id': '6', 'val': '5M', 'date':Timestamp('2000-01-03 00:00:00')}),
(Timestamp('2000-01-03 00:00:00'),
{'id': '1', 'val': '25M', 'date':Timestamp('2000-01-03 00:00:00')}),
(Timestamp('2000-01-03 00:00:00'),
{'id': '2', 'val': '7M', 'date':Timestamp('2000-01-03 00:00:00')}),
我正在尝试运行一个reduceByKey
功能,它给了我:
[ (Timestamp('2000-01-01 00:00:00'),
[{'id': '1', 'val': '200M', 'date':Timestamp('2000-01-01 00:00:00')},
{'id': '2', 'val': '10M', 'date':Timestamp('2000-01-01 00:00:00')},
{'id': '3', 'val': '30M', 'date':Timestamp('2000-01-01 00:00:00')}]),
(Timestamp('2000-01-02 00:00:00'),
[{'id': '15', 'val': '120M', 'date':Timestamp('2000-01-02 00:00:00')},
{'id': '3', 'val': '35M', 'date':Timestamp('2000-01-02 00:00:00')},
{'id': '4', 'val': '56M', 'date':Timestamp('2000-01-02 00:00:00')}]),
(Timestamp('2000-01-03 00:00:00'),
[{'id': '6', 'val': '5M', 'date':Timestamp('2000-01-03 00:00:00')},
{'id': '1', 'val': '25M', 'date':Timestamp('2000-01-03 00:00:00')},
{'id': '2', 'val': '7M', 'date':Timestamp('2000-01-03 00:00:00')}]) ]
到目前为止,我已经尝试过:
output = rdd.flatMap(split_func).reduceByKey(lambda x, y: x+y).collect()
但我收到此错误:
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
提前致谢!
解决方案
这更像是一个python错误。如果d1
和d2
是字典,则d1 + d2
不起作用。但是,您可以这样做{**d1, **d2}
。如果 d1 和 d2 具有相同的键,它将从 d2 中获取值。
所以你可以做output = rdd.flatMap(split_func).reduceByKey(lambda x, y: {**x, **y}).collect()
但是,您的结果是一个元组列表。所以在这种情况下,我认为 groupByKey 更好:output = rdd.flatMap(split_func).groupByKey().mapValues(list).collect()
推荐阅读
- python-3.x - 将宽数据帧转换为具有特定条件并添加新列的长数据帧
- docker - 在领事注册后如何解决无尘室不接服务的问题
- reactjs - React 应用程序在登录后几秒钟就退出了 safari,但在 chrome 和其他 Web 浏览器上运行良好
- excel - 无法使用 Key 访问类模块集合,“运行时错误 13 - 类型不匹配”
- javascript - 这是比较两个对象数组和修改属性的最有效的 JavaScript 吗?
- authorization - 共享资源的 Keycloak 决策策略不起作用
- c# - ClosedXML 模板未将数据设置到 Excel 工作表中
- php - Symfony 使用构造函数反序列化对象
- spring - 具有安全性的 Spring Boot Starter - Okta oauth2 的问题
- tensorflow - TensorFlow中如何清除整个网络结构