concept reduce in category data

appears as: reduce
Mastering Large Datasets with Python: Parallelize and Distribute Your Python Code

This is an excerpt from Manning's book Mastering Large Datasets with Python: Parallelize and Distribute Your Python Code.

This book teaches a set of programming techniques, tools, and frameworks for mastering large datasets. Throughout this book, I’ll refer to the style of programming you’re learning as a map and reduce style. The map and reduce style of programming is one in which we can easily write parallel programs—programs that can do multiple things at the same time—by organizing our code around two functions: map and reduce. To get a better sense of why we’ll want to use a map and reduce style, consider this scenario:

Figure 1.7. The functions map and reduce are often used together to perform complex transformations of large amounts of data quickly.

In chapter 2, we learned about the first part of the map and reduce style of programming: map. In this chapter, we introduce the second part: reduce. As we noted in chapter 2, map performs N-to-N transformations. That is, if we have a situation where we want to take a sequence and get a same-sized sequence back, map is our go-to function. Among the examples of this that we’ve reviewed are file processing (we have a list of files and we want to do something to all of them; discussed in chapter 4) and web scraping (we have a list of websites and we want to get the content for each of them; discussed in chapter 2).

In this chapter, we’ll focus on reduce for N-to-X transformations; that is, situations where we have some sequence but we want to get something back besides another same-sized sequence, usually a sequence of a different size or possibly not even a sequence at all. Note, however, that situations do exist where we’ll actually want to use reduce to get back a sequence of the same size. We’ll look at all of these situations, learning about reduce and using it in some common transformations that you’re already familiar with. Learning reduce will give us a handy tool to use in situations where map isn’t appropriate, but where we still want to benefit from using a common programming pattern.

5.1. N-to-X with reduce

When we say that reduce is a function for N-to-X transformations, we mean that whenever we have a sequence and want to transform it into something that we can’t use map for, we can happily use reduce. This is one of the reasons why map and reduce pair so neatly together: map can take care of most of the transformations in a very concise manner, whereas reduce can take care of the very final transformation, albeit in a somewhat less elegant fashion.

Listing 5.3. Lambda function inside reduce for summation
from functools import reduce

xs = [10, 5, 1, 19, 11, 203]
print(reduce(lambda acc, nxt: acc+nxt, xs, 0))    #1