Python中的MRJob排序

2024-10-03 19:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个任务要求我使用python中的mapper/reducer来完成客户数据的MapReduce。我有一个CSV文件,其中包含CustomerID、ProductID和花费的金额。第一个任务是确定每个客户的总花费,我很容易就完成了。下一部分要求我取下这个清单,并按花费总额的降序排序。我在这里挣扎。。。建议在另一个MapReduce之上使用MapReduce。以下是我的代码:

第1部分:

from mrjob.job import MRJob

class TotalAmountCust(MRJob):

    def mapper(self, _, line):
        (customerid, idno, amount) = line.split(',')
        yield customerid, float(amount)

    def reducer(self, customerid, amount):
        yield customerid, sum(amount)

if __name__ == '__main__':
    TotalAmountCust.run()

第2部分:

^{pr2}$

第2部分有一个问题,根本不会给我一个结果。任何建议都会被很好地推荐。。。我试图研究MRJob.SORT_值是的,但这并没有给我带来我希望的结果。在


Tags: 数据self客户deflineamount建议花费
1条回答
网友
1楼 · 发布于 2024-10-03 19:27:54

我解决了,现在命令输出

from mrjob.job import MRJob
from mrjob.step import MRStep

class SpendByCustomerSorted(MRJob):

    MRJob.SORT_VALUES = True

    def steps(self):
        return [
            MRStep(mapper=self.mapper_get_orders,
                   reducer=self.reducer_totals_by_customer),
            MRStep(mapper=self.mapper_make_amounts_key,
                   reducer=self.reducer_output_results_for_single_reducer)
        ]
    def mapper_get_orders(self, _, line):
        (customerID, itemID, orderAmount) = line.split(',')
        yield customerID, float(orderAmount)

    def reducer_totals_by_customer(self, customerID, orders):
        yield customerID, sum(orders)

    def mapper_make_amounts_key(self, customerID, orderTotal):
        yield None, ("%07.02f"%float(orderTotal), customerID)

    def reducer_output_results(self, n, orderTotalCustomerIDs):
        for c in orderTotalCustomerIDs:
            yield c[1], c[0]

if __name__ == '__main__':
    SpendByCustomerSorted.run()

相关问题 更多 >