我有两个来自 map 函数的关键值:NY和其他。因此,我的密钥的输出为:NY 1或Other1。仅这两种情况。
我的 map 功能:
#!/usr/bin/env python
import sys
import csv
import string
reader = csv.reader(sys.stdin, delimiter=',')
for entry in reader:
if len(entry) == 22:
registration_state=entry[16]
print('{0}\t{1}'.format(registration_state,int(1)))
现在,我需要使用reducer来处理 map 输出。我的减少:
#!/usr/bin/env python
import sys
import string
currentkey = None
ny = 0
other = 0
# input comes from STDIN (stream data that goes to the program)
for line in sys.stdin:
#Remove leading and trailing whitespace
line = line.strip()
#Get key/value
key, values = line.split('\t', 1)
values = int(values)
#If we are still on the same key...
if key == 'NY':
ny = ny + 1
#Otherwise, if this is a new key...
else:
#If this is a new key and not the first key we've seen
other = other + 1
#Compute/output result for the last key
print('{0}\t{1}'.format('NY',ny))
print('{0}\t{1}'.format('Other',other))
通过这些,mapreduce将提供两个输出结果文件,每个文件都包含NY和Others输出。即,其中包含:NY 1248,其他4677;另一个:NY 0,其他1000。这是因为两个减法从 map 上拆分了输出,所以生成了两个结果,通过合并(合并)最终输出将是结果。
但是,我想将我的reduce或map函数更改为仅对一个键进行每个简化的过程,即一个reduce仅将NY作为键值,而另一个对Other处理。我希望得到类似以下结果的结果:
NY 1258, Others 0; Another: NY 0, Others 5677.
如何调整功能以达到预期效果?
最佳答案
可能您需要使用Python迭代器和生成器。
这个link就是一个很好的例子。我尝试用相同的代码重新编写代码(未经测试)
映射器:
#!/usr/bin/env python
"""A more advanced Mapper, using Python iterators and generators."""
import sys
def main(separator='\t'):
reader = csv.reader(sys.stdin, delimiter=',')
for entry in reader:
if len(entry) == 22:
registration_state=entry[16]
print '%s%s%d' % (registration_state, separator, 1)
if __name__ == "__main__":
main()
reducer :
!/usr/bin/env python
"""A more advanced Reducer, using Python iterators and generators."""
from itertools import groupby
from operator import itemgetter
import sys
def read_mapper_output(file, separator='\t'):
for line in file:
yield line.rstrip().split(separator, 1)
def main(separator='\t'):
for current_word, group in groupby(data, itemgetter(0)):
try:
total_count = sum(int(count) for current_word, count in group)
print "%s%s%d" % (current_word, separator, total_count)
except ValueError:
# count was not a number, so silently discard this item
pass
if __name__ == "__main__":
main()
关于python - 如何通过识别python Hadoop中的键来处理Mapreduce,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49085928/