2键Python的MapReduce Reducer

2024-04-25 18:55:29 发布

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

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

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

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

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

^{pr2}$

每个名称都需要有自己的二进制密钥0或1。根据二进制键,求count列的和。注意所需输出中的“reduce”。在

我已经提供了我的一些代码,我试图在reducer中不使用列表或字典。在

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

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

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

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}')

由于某些原因,它没有正确打印。(通过的名字很有趣)我也不确定通过所有打印的一个或零个计数也显示其二进制标签的最佳方法。在

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


Tags: name名称示例ifcount二进制currentone
2条回答

压痕不好,处理不当。在

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”和“one”count,并对新的“current”进行了计算。在

我的代码的输出:

^{pr2}$

我认为最好使用熊猫图书馆。在

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或文本文件中。它可以用熊猫来阅读。在

^{pr2}$

相关问题 更多 >