Skip to content
Advertisement

Calculating the averages for each KEY in a Pairwise (K,V) RDD in Spark with Python

I want to share this particular Apache Spark with Python solution because documentation for it is quite poor.

I wanted to calculate the average value of K/V pairs (stored in a Pairwise RDD), by KEY. Here is what the sample data looks like:

JavaScript

Now the following code sequence is a less than optimal way to do it, but it does work. It is what I was doing before I figured out a better solution. It’s not terrible but — as you’ll see in the answer section — there is a more concise, efficient way.

JavaScript

Advertisement

Answer

Now a much better way to do this is to use the rdd.aggregateByKey() method. Because this method is so poorly documented in the Apache Spark with Python documentation — and is why I wrote this Q&A — until recently I had been using the above code sequence. But again, it’s less efficient, so avoid doing it that way unless necessary.

Here’s how to do the same using the rdd.aggregateByKey() method (recommended):

By KEY, simultaneously calculate the SUM (the numerator for the average that we want to compute), and COUNT (the denominator for the average that we want to compute):

JavaScript

Where the following is true about the meaning of each a and b pair above (so you can visualize what’s happening):

JavaScript

Finally, calculate the average for each KEY, and collect results.

JavaScript

I hope this question and answer with aggregateByKey() will help.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement