pyspark - 带有 (key, (key2, value)) 的 RDD
问题描述
我在 pyspark 中有一个形式为(键,其他东西)的 RDD,其中“其他东西”是字段列表。我想从字段列表中获取另一个使用第二个键的 RDD。例如,如果我的初始 RDD 是:
(User1, 1990 4 2 绿色...)
(User1, 1990 2 2 绿色...)
(User2, 1994 3 8 蓝色...)
(User1, 1987 3 4 蓝色...)
我想得到 (User1, [(1990, x), (1987, y)]),(User2, (1994 z))
其中 x, y, z 将是其他字段的聚合,例如 x 是我在 User1 和 1990 中拥有的行数(在本例中为两个),并且我得到一个每年包含一个元组的列表。
我正在查看来自以下位置的键值函数: https ://www.oreilly.com/library/view/learning-spark/9781449359034/ch04.html
但似乎没有找到任何可以提供和聚合两次的东西:一次用于用户,一次用于一年。我最初的尝试是使用 combineByKey() 但我被困在从值中获取列表。
任何帮助,将不胜感激!
解决方案
您可以使用以下方法执行以下操作groupby
:
# sample rdd
l = [("User1", "1990"),
("User1", "1990"),
("User2", "1994"),
("User1", "1987") ]
rd = sc.parallelize(l)
# returns a tuples of count of year
def f(l):
dd = {}
for i in l:
if i not in dd:
dd[i] =1
else:
dd[i]+=1
return list(dd.items())
# using groupby and applying the function on x[1] (which is a list)
rd1 = rd.groupByKey().map(lambda x : (x[0], f(x[1]))).collect()
[('User1', [('1990', 2), ('1987', 1)]), ('User2', [('1994', 1)])]
推荐阅读
- android - firebase 身份验证 sendVerificationEmail() 任务需要永远
- javascript - Codemirror 自动完成功能不适用于 javascript
- reactjs - pusher .bind 方法中的过时反应状态
- html - 如何使用引导程序中的列构建以下设计?
- django - 我如何过滤字段 django jsonfield 是日期时间?
- c++ - Qt subdirs:使用通用源文件
- c# - 将数据插入(第 30 列,第 1 行)
- couchdb - couchdb _find 安全,过滤 _find 返回结果
- javascript - JS - 如何根据从其他 textarea 输入镜像的输入文本自动调整 textarea 的大小?
- r - R:在 R 中循环和可视化“运行时间”