05-07-2020, 12:48 AM
How to Average a List of Lists in Python?
<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="python column average list of lists" width="1400" height="788" src="https://www.youtube.com/embed/zUYaG3waoiI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Problem</strong>: You have a list of lists and you want to calculate the average of the different columns.</p>
<p><strong>Example</strong>: Given the following list of lists with four rows and three columns.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]]</pre>
<p>You want to have the average values of the three columns:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[average_col_1, average_col_2, average_col_3]</pre>
<p>There are three methods that solve this problem. You can play with them in the interactive shell and read more details below:</p>
<figure><iframe src="https://repl.it/@finxter/listoflistsaverage?lite=true" allowfullscreen="true" width="100%" height="1000px"></iframe></figure>
<h2>Method 1: Average in Python (No Library)</h2>
<p>A simple one-liner with <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> in combination with the <a rel="noreferrer noopener" href="https://blog.finxter.com/zip-unzip-python/" target="_blank"><code>zip()</code> function</a> on the <a href="https://blog.finxter.com/what-is-asterisk-in-python/">unpacked list</a> to transpose the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">list of lists</a> does the job in Python. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 1: Pure Python
res = [sum(x) / len(x) for x in zip(*data)]
print(res)
# [0.5, 0.75, 0.25]</pre>
<p>Do you love Python one-liners? I do for sure—I’ve even written a whole book about it with San Francisco Publisher NoStarch. Click to check out the book in a new tab:</p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/04/3D_transparent-300x277.png" alt="Python One-Liners Book" class="wp-image-7439" width="150" height="139" srcset="https://blog.finxter.com/wp-content/uploads/2020/04/3D_transparent-300x277.png 300w, https://blog.finxter.com/wp-content/uplo...parent.png 1024w, https://blog.finxter.com/wp-content/uplo...68x708.png 768w" sizes="(max-width: 150px) 100vw, 150px" /></a></figure>
<p>You can visualize the code execution and memory objects of this code in the following tool (just click “Next” to see how one step of the code unfolds).</p>
<p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=data%20%3D%20%5B%5B0,%201,%200%5D,%0A%20%20%20%20%20%20%20%20%5B1,%201,%201%5D,%0A%20%20%20%20%20%20%20%20%5B0,%200,%200%5D,%0A%20%20%20%20%20%20%20%20%5B1,%201,%200%5D%5D%0A%0A%0Ares%20%3D%20%5Bsum%28x%29%20/%20len%28x%29%20for%20x%20in%20zip%28*data%29%5D%0Aprint%28res%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<h2>Method 2: Average with NumPy Library</h2>
<p>You create a <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy array</a> out of the data and pass it to the <a href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/" target="_blank" rel="noreferrer noopener">np.average()</a> function. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 2: NumPy
import numpy as np
a = np.array(data)
res = np.average(a, axis=0)
print(res)
# [0.5 0.75 0.25]</pre>
<p>The <code>axis</code> argument of the average function defines along which axis you want to calculate the average value. If you want to average columns, define <code>axis=0</code>. If you want to average rows, define <code>axis=1</code>. If you want to average over all values, skip this argument. </p>
<h2>Method 3: Mean Statistics Library + Map()</h2>
<p>Just to show you another alternative, here’s one using the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank"><code>map()</code> function</a> and our <code>zip(*data)</code> trick to transpose the “matrix” <code>data</code>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 3: Statistics + Map()
import statistics
res = map(statistics.mean, zip(*data))
print(list(res))
# [0.5, 0.75, 0.25]</pre>
<p>The <code>map(function, iterable)</code> function applies <code>function</code> to each element in <code>iterable</code>. As an alternative, you can also use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension-python-list-of-lists/" target="_blank">list comprehension</a> as shown in method 1 in this tutorial. In fact, Guido van Rossum, the creator of Python and Python’s benevolent dictator for life (BDFL), <a rel="noreferrer noopener" href="https://blog.finxter.com/about-guidos-fate-of-reduce-in-python-3000/" target="_blank">prefers list comprehension over the <code>map()</code> function</a>. </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>
https://www.sickgaming.net/blog/2020/05/...in-python/
<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="python column average list of lists" width="1400" height="788" src="https://www.youtube.com/embed/zUYaG3waoiI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Problem</strong>: You have a list of lists and you want to calculate the average of the different columns.</p>
<p><strong>Example</strong>: Given the following list of lists with four rows and three columns.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]]</pre>
<p>You want to have the average values of the three columns:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[average_col_1, average_col_2, average_col_3]</pre>
<p>There are three methods that solve this problem. You can play with them in the interactive shell and read more details below:</p>
<figure><iframe src="https://repl.it/@finxter/listoflistsaverage?lite=true" allowfullscreen="true" width="100%" height="1000px"></iframe></figure>
<h2>Method 1: Average in Python (No Library)</h2>
<p>A simple one-liner with <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> in combination with the <a rel="noreferrer noopener" href="https://blog.finxter.com/zip-unzip-python/" target="_blank"><code>zip()</code> function</a> on the <a href="https://blog.finxter.com/what-is-asterisk-in-python/">unpacked list</a> to transpose the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" target="_blank">list of lists</a> does the job in Python. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 1: Pure Python
res = [sum(x) / len(x) for x in zip(*data)]
print(res)
# [0.5, 0.75, 0.25]</pre>
<p>Do you love Python one-liners? I do for sure—I’ve even written a whole book about it with San Francisco Publisher NoStarch. Click to check out the book in a new tab:</p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/04/3D_transparent-300x277.png" alt="Python One-Liners Book" class="wp-image-7439" width="150" height="139" srcset="https://blog.finxter.com/wp-content/uploads/2020/04/3D_transparent-300x277.png 300w, https://blog.finxter.com/wp-content/uplo...parent.png 1024w, https://blog.finxter.com/wp-content/uplo...68x708.png 768w" sizes="(max-width: 150px) 100vw, 150px" /></a></figure>
<p>You can visualize the code execution and memory objects of this code in the following tool (just click “Next” to see how one step of the code unfolds).</p>
<p> <iframe width="800" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code=data%20%3D%20%5B%5B0,%201,%200%5D,%0A%20%20%20%20%20%20%20%20%5B1,%201,%201%5D,%0A%20%20%20%20%20%20%20%20%5B0,%200,%200%5D,%0A%20%20%20%20%20%20%20%20%5B1,%201,%200%5D%5D%0A%0A%0Ares%20%3D%20%5Bsum%28x%29%20/%20len%28x%29%20for%20x%20in%20zip%28*data%29%5D%0Aprint%28res%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false"> </iframe> </p>
<h2>Method 2: Average with NumPy Library</h2>
<p>You create a <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy array</a> out of the data and pass it to the <a href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/" target="_blank" rel="noreferrer noopener">np.average()</a> function. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 2: NumPy
import numpy as np
a = np.array(data)
res = np.average(a, axis=0)
print(res)
# [0.5 0.75 0.25]</pre>
<p>The <code>axis</code> argument of the average function defines along which axis you want to calculate the average value. If you want to average columns, define <code>axis=0</code>. If you want to average rows, define <code>axis=1</code>. If you want to average over all values, skip this argument. </p>
<h2>Method 3: Mean Statistics Library + Map()</h2>
<p>Just to show you another alternative, here’s one using the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank"><code>map()</code> function</a> and our <code>zip(*data)</code> trick to transpose the “matrix” <code>data</code>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data = [[0, 1, 0], [1, 1, 1], [0, 0, 0], [1, 1, 0]] # Method 3: Statistics + Map()
import statistics
res = map(statistics.mean, zip(*data))
print(list(res))
# [0.5, 0.75, 0.25]</pre>
<p>The <code>map(function, iterable)</code> function applies <code>function</code> to each element in <code>iterable</code>. As an alternative, you can also use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension-python-list-of-lists/" target="_blank">list comprehension</a> as shown in method 1 in this tutorial. In fact, Guido van Rossum, the creator of Python and Python’s benevolent dictator for life (BDFL), <a rel="noreferrer noopener" href="https://blog.finxter.com/about-guidos-fate-of-reduce-in-python-3000/" target="_blank">prefers list comprehension over the <code>map()</code> function</a>. </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>
https://www.sickgaming.net/blog/2020/05/...in-python/