首页 > 解决方案 > 带有 (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() 但我被困在从值中获取列表。

任何帮助,将不胜感激!

标签: pysparkrdd

解决方案


您可以使用以下方法执行以下操作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)])]

推荐阅读