2键的MapReduce Reducer-Python

时间:2018-09-21 00:24:28

标签: python hadoop mapreduce hadoop-streaming reducers

这应该很简单,我已经花了几个小时了。

示例数据(名称,二进制,计数):

Adam 0 1
Adam 1 1
Adam 0 1
Mike 1 1
Mike 0 1
Mike 1 1  

所需的示例输出(名称,二进制,计数):

Adam 0 2
Adam 1 1
Mike 0 1
Mike 1 2  

每个名称都必须具有自己的二进制密钥0或1。根据二进制密钥,对count列求和。注意所需输出中的“减少”。

我已经提供了一些代码,并且我试图在化简器中没有列表或字典

“”“ Reducer用二进制文件获取名称,部分计数将它们加起来

输入:     名称\ t二进制\ t pCount

输出:     名称\ t二进制\ t tCount
“”“

import re
import sys

current_name = None
zero_count, one_count = 0,0

for line in sys.stdin:
    # parse the input
    name, binary, count = line.split('\t')

   if name == current_name:
      if int(binary) == 0:
        zero_count += int(count)

    elif int(binary) == 1:
        one_count += int(count)
else:
    if current_name:
        print(f'{current_name}\t{0} \t{zero_count}')
        print(f'{current_name}\t{1} \t{one_count}')
    current_name, binary, count = word, int(binary), int(count)

print(f'{current_name}\t{1} \t{count}')

由于某种原因,它无法正确打印。 (通过的名字很时髦)我也不确定通过one_count和zero_count同时显示其二进制标签的所有打印的最佳方式。

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

我认为最好使用熊猫库。

import pandas as pd
from io import StringIO
a ="""Adam 0 1
Adam 1 1
Adam 0 1
Mike 1 1
Mike 0 1
Mike 1 1"""

text = StringIO(a)
name, binary, count = [],[],[]

for line in text.readlines():
    a = line.strip().split(" ")
    name.append(a[0])
    binary.append(a[1])
    count.append(a[2])

df = pd.DataFrame({'name': name, "binary": binary, "count": count})
df['count'] = df['count'].astype(int)
df = df.groupby(['name', 'binary'])['count'].sum().reset_index()
print(df)
name    binary  count
0   Adam    0   2
1   Adam    1   1
2   Mike    0   1
3   Mike    1   2

如果您的数据已经在csv或文本文件中。可以使用熊猫阅读。

df = pd.read_csv('path to your file')

答案 1 :(得分:0)

压痕不好,条件处理不当。

import re
import sys

current_name = None
zero_count, one_count = 0,0
i = 0
for line in sys.stdin:
    # parse the input
    name, binary, count = line.split('\t')
    #print(name)
    #print(current_name)
    if(i == 0):
        current_name = name
        i  = i + 1
    if(name == current_name):
        if int(binary) == 0:
            zero_count += int(count)

        elif int(binary) == 1:
            one_count += int(count)
    else:
        print(f'{current_name}\t{0} \t{zero_count}')
        print(f'{current_name}\t{1} \t{one_count}')
        current_name = name
        #print(current_name)
        zero_count, one_count = 0,0
        if int(binary) == 0:
            zero_count += int(count)
        elif int(binary) == 1:
            one_count += int(count)
print(f'{current_name}\t{0} \t{zero_count}')
print(f'{current_name}\t{1} \t{one_count}')

'i'处理第一行输入没有'current_name'的情况(它只会运行一次)。
在else块中,您已经重新初始化了“ zero_count”和“ one_count”,并且还为新的“ current_name”进行了计算。

我的代码的输出:

Adam    0       2
Adam    1       1
Mike    0       1
Mike    1       2