如何在Python mapreduce reducer部分中使用多个键聚合输出

问题描述

我在进行mapreduce方面还很陌生,我正在尝试执行以下操作:

我创建了一个映射器,它产生以下结果:

12,United Kingdom:17850 15.3
12,United Kingdom:17850 20.34
12,United Kingdom:17850 22.0
12,United Kingdom:17850 25.5
12,United Kingdom:17850 11.1
12,United Kingdom:13047 54.08
12,United Kingdom:13047 12.6
12,United Kingdom:13047 30.0
12,United Kingdom:13047 9.9

结果包含月份,国家/地区:客户花费的客户

我的mapper.py如下所示:

#!/usr/bin/env python


import sys
import re
from datetime import datetime
 
infile = sys.stdin
next(infile) 
for line in infile:
    line = line.strip()
    columns = line.split(',')
    
    cust_ID = columns[6]
    country = columns[7]
    date = columns[4]
    date = datetime.strptime(date,'%m/%d/%Y %H:%M')
    M = '%02d' % date.month
    price = float(columns[5])
    qty = int(columns[3])
    
    print '%s,%s:%s\t%s' % (M,country,cust_ID,(price*qty))

由于我的最终目标是按月和国家/地区汇总结果,因此该值将成为每个月和国家/地区组合的最大支出客户,因此我在减速器部分上非常棘手。最终结果如下所示: Month,Country:Customer

我当前的reducer.py如下所示:

#!/usr/bin/env python

import sys
import re
 
current_key = None
current_value = 0
key = None
cur_month_country_key = None
cur_cust_id = None

for line in sys.stdin:
  line = line.strip()
  key,value = line.split('\t',1)
  month_country_key,cust_id = key.split(':')
  value = float(value)
  if current_key == key:
    current_value += value
  else:
    if current_key:
      print('%s:%f' % (current_key,current_value))
    current_value = value
    current_key = key
if current_key == key:
    print('%s:%f' % (current_key,current_value))

从中我可以得到以下结果:

01,Australia:12386:143.000000
01,Australia:12388:431.300000
01,Australia:12393:639.500000
01,Australia:12415:7092.980000
01,Australia:12422:238.500000
01,Australia:12431:384.680000
01,Australia:16321:87.750000
01,Belgium:12383:651.160000

结果为月,country:customer:customerTotal

但是,这并不是我的期望输出,因为我一直坚持如何进一步整合减速器,以便按月(国家/地区为关键)进行聚合,按花费的最高客户排序,然后得出月份,国家/地区:客户

任何对如何进行我的减速器的投入将不胜感激。我虽然创建了一个字典来存储键-值对,但是由于我需要两个字典,因此被卡住了。一个用于当前月份,国家:客户密钥,另一个用于客户和总支出。任何建议将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)