【问题标题】:pyspark adding values with common set of keys (python)pyspark 使用公共键集添加值(python)
【发布时间】:2020-07-28 17:03:09
【问题描述】:

我有这个 RDD:

[('19', '1004', '129'),
 ('17', '1004', '129'),
 ('9', '1001', '99'),
 ('3', '1003', '89'),
 ('19', '1002', '149'),
 ('16', '1002', '149'),
 ('16', '1002', '149')]

我只想在两个键都匹配时才添加值。 例如:

('**16**', '**1002**', '149'),
('**16**', '**1002**', '149')

想要的输出是

[('19', '1004', '129'),
 ('17', '1004', '129'),
 ('9', '1001', '99'),
 ('3', '1003', '89'),
 ('19', '1002', '149'),
 ('16', '1002', '298')]

【问题讨论】:

    标签: python pyspark jupyter-notebook


    【解决方案1】:

    您想要的函数是reduceByKey(),但您的数据不是该函数可以使用的格式。

    • 您需要将字符串值转换为整数值
    • 您需要将元组从(k1, k2, v) 形式转换为((k1, k2), v)

    这应该可以工作:

    # Prepare for reduce operation
    r = r.map(lambda t: ((t[0], t[1]), int(t[2])))
    
    # Add matching items
    from operator import add
    r = r.reduceByKey(add)
    
    # If desired, convert back to your original form
    r = r.map(lambda t: (t[0][0], t[0][1], str(t[1])))
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      相关资源
      最近更新 更多