【问题标题】:RDD with (key, (key2, value))带有 (key, (key2, value)) 的 RDD
【发布时间】:2019-01-01 10:55:00
【问题描述】:

我在 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() 但我被困在从值中获取列表中。

任何帮助将不胜感激!

【问题讨论】:

    标签: pyspark rdd


    【解决方案1】:

    您可以使用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)])]
    

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2015-03-22
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      相关资源
      最近更新 更多