[英]pyspark adding values with common set of keys (python)
我有這個 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')
所需的 output 是
[('19', '1004', '129'),
('17', '1004', '129'),
('9', '1001', '99'),
('3', '1003', '89'),
('19', '1002', '149'),
('16', '1002', '298')]
您想要的 function 是reduceByKey()
,但您的數據並不是該 function 可以使用的格式。
(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])))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.