<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>2D array Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/tag/2d-array/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/tag/2d-array/</link>
	<description></description>
	<lastBuildDate>Fri, 17 Nov 2023 11:19:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>2D array Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/tag/2d-array/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Calculate the Weighted Average of a Numpy Array in Python?</title>
		<link>https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sun, 14 Feb 2021 12:13:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[2D array]]></category>
		<category><![CDATA[Average]]></category>
		<category><![CDATA[axis]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[Numpy Array]]></category>
		<category><![CDATA[Python 3]]></category>
		<category><![CDATA[weight]]></category>
		<category><![CDATA[weighted average]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=477</guid>

					<description><![CDATA[<p>Problem Formulation: How to calculate the weighted average of the elements in a NumPy array? Definition weighted average: Each array element has an associated weight. The weighted average is the sum of all array elements, properly weighted, divided by the sum of all weights. Here&#8217;s the problem exemplified: Quick solution: Before we discuss the solution ... <a title="How to Calculate the Weighted Average of a Numpy Array in Python?" class="read-more" href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/" aria-label="Read more about How to Calculate the Weighted Average of a Numpy Array in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/">How to Calculate the Weighted Average of a Numpy Array in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><strong>Problem Formulation:</strong> How to calculate the weighted average of the elements in a NumPy array?</p>



<p><strong>Definition weighted average: </strong>Each array element has an associated weight. The weighted average is the sum of all array elements, properly weighted, divided by the sum of all weights.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="705" height="115" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-61.png" alt="" class="wp-image-23953" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-61.png 705w, https://blog.finxter.com/wp-content/uploads/2021/02/image-61-300x49.png 300w" sizes="(max-width: 705px) 100vw, 705px" /></figure>
</div>


<p>Here&#8217;s the problem exemplified:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-1024x576.jpg" alt="Weighted Average of NumPy Array - Problem Example" class="wp-image-23956" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2021/02/weighted_average_problem-768x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>


<p><strong>Quick solution:</strong> Before we discuss the solution in great detail, here&#8217;s the solution that solves this exact problem:</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="">import numpy as np

array = np.array([[1, 0, 2],
                  [1, 1, 1]])
weights = np.array([[2, 1, 1],
                    [1, 1, 2]])

print(np.average(array, weights=weights))
# 1.0</pre>



<p>Want to learn how it works&#8212;and how you can average along an axis as well? Let&#8217;s dive deeper into the problem next!</p>



<h2 class="wp-block-heading">Weighted Average with NumPy&#8217;s np.average() Function</h2>



<p>NumPy&#8217;s <code><a href="https://blog.finxter.com/numpy-average/" title="NumPy Average">np.average(arr)</a></code> function computes the average of all numerical values in a NumPy array. When used with only one array argument, it calculates the numerical average of all values in the array, no matter the array&#8217;s dimensionality. For example, the expression <code>np.average([[1,2],[2,3]])</code> results in the average value <code>(1+2+2+3)/4 = 2.0</code>.</p>



<p>However, what if you want to calculate the <strong>weighted average</strong> of a NumPy array? In other words, you want to <em>overweigh</em>t some array values and <em>underweigh</em>t others.</p>



<p>You can easily accomplish this with NumPy&#8217;s <a href="https://blog.finxter.com/how-to-average-a-list-of-lists-in-python/" target="_blank" rel="noreferrer noopener">average </a>function by passing the weights argument to the NumPy <code><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html" target="_blank" rel="noreferrer noopener" title="https://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html">average</a></code> 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="">import numpy as np

a = [-1, 1, 2, 2]

print(np.average(a))
# 1.0

print(np.average(a, weights = [1, 1, 1, 5]))
# 1.5</pre>



<p>In the first example, we simply averaged over all array values: <code>(-1+1+2+2)/4 = 1.0</code>. However, in the second example, we overweight the last array element 2&#8212;it now carries five times the weight of the other elements resulting in the following computation: <code>(-1+1+2+(2+2+2+2+2))/8 = 1.5</code>.</p>



<h2 class="wp-block-heading">NumPy Weighted Average Video</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How to Calculate the Weighted Average of a Numpy Array in Python?" width="937" height="527" src="https://www.youtube.com/embed/b0U31GkE7ho?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">NumPy Average Syntax</h2>



<p>Let&#8217;s explore the different parameters we can pass to <code>np.average(...)</code>.</p>



<ul class="wp-block-list">
<li><strong>The NumPy array</strong> which can be multi-dimensional.</li>



<li>(Optional) <strong>The axis</strong> along which you want to average. If you don&#8217;t specify the argument, the averaging is done over the whole array.</li>



<li>(Optional) <strong>The weights</strong> of each column of the specified axis. If you don&#8217;t specify the argument, the weights are assumed to be homogeneous.</li>



<li>(Optional) <strong>The return value</strong> of the function. Only if you set this to True, you will get a tuple (average, weights_sum) as a result. This may help you to normalize the output. In most cases, you can skip this argument.</li>
</ul>



<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(a, axis=None, weights=None, returned=False)</pre>



<figure class="wp-block-table is-style-stripes"><table><thead><tr><th>Argument</th><th>Description</th></tr></thead><tbody><tr><td><code>a</code></td><td><em><strong>array-like</strong></em>: The array contains the data to be averaged. Can be multi-dimensional and it doesn’t have to be a NumPy array—but usually, it is.</td></tr><tr><td><code>axis=None</code></td><td><strong><em>None or int or tuple of ints:</em></strong> The axis along which to average the array <code>a</code>.</td></tr><tr><td><code>weights=None</code></td><td><em><strong>array-like</strong></em>: An array of weights associated to the values in the array <code>a</code>. This allows you to customize the weight towards the average of each element in the array.</td></tr><tr><td><code>returned=False</code></td><td><strong><em>Boolean</em></strong>: If <code>False</code>, returns the average value. If <code>True</code>, returns the tuple of the <code>(average, sum_of_weights)</code> so that you can easily normalize the weighted average.</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">NumPy Weighted Average Along an Axis (Puzzle)</h2>



<p>Here is an example how to <a href="https://blog.finxter.com/numpy-average-along-axis/" target="_blank" rel="noreferrer noopener">average along the columns</a> of a 2D NumPy array with specified weights for both rows.</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="">import numpy as np

# daily stock prices
# [morning, midday, evening]
solar_x = np.array(
    [[2, 3, 4], # today
     [2, 2, 5]]) # yesterday

# midday - weighted average
print(np.average(solar_x, axis=0, weights=[3/4, 1/4])[1])</pre>



<p><em>What is the output of this puzzle?</em><br>*Beginner Level* (solution below)</p>



<p>You can also solve this puzzle in our puzzle-based learning app (100% FREE):<a href="https://app.finxter.com/learn/computer/science/433" target="_blank" rel="noreferrer noopener">&nbsp;Test your skills now!</a></p>



<h2 class="wp-block-heading">Puzzle Explanation</h2>



<p>Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.</p>



<p>This puzzle introduces the average function from the NumPy library. When applied to a 1D NumPy array, this function returns the average of the array values. When applied to a 2D NumPy array, it simply flattens the array. The result is the average of the flattened 1D array.</p>



<p>In the puzzle, we have a matrix with two rows and three columns. The matrix gives the stock prices of the <code>solar_x</code> stock. Each row represents the prices for one day. The first column specifies the morning price, the second the midday price, and the third the evening price.</p>



<p>Now suppose, we do not want to know the <a href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/" target="_blank" rel="noreferrer noopener" title="How to Calculate the Average of a NumPy 2D Array?">average of the flattened matrix</a> but the average of the price in the midday. Moreover, we want to overweight the most recent stock price. Today accounts for three-quarters and yesterday for one-quarter of the final average value.</p>



<p><a href="https://blog.finxter.com/numpy-tutorial/" title="NumPy Tutorial – Everything You Need to Know to Get Started" target="_blank" rel="noreferrer noopener">NumPy </a>enables this via the <code>weights</code> parameter in combination with the <code>axis</code> parameter.</p>



<ul class="wp-block-list">
<li>The <code>weights</code> parameter defines the weight for each value participating in the average calculation. </li>



<li>The <code>axis</code> parameter specifies the direction along which the average should be calculated.</li>
</ul>



<p>In a 2D matrix, the row is specified as <code>axis=0</code> and the column as <code>axis=1</code>. We want to know three average values, for the morning, midday, and evening. We calculate the average along the row, i.e., <code>axis=0</code>. This results in three average values. Now we take the second element to get the midday variance.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-to-normalize-a-numpy-matrix/" data-type="post" data-id="1045844" target="_blank" rel="noreferrer noopener">How to Normalize a NumPy Matrix</a></p>



<h2 class="wp-block-heading">Where to Go From Here?</h2>



<p>Want to thrive in data science? Master NumPy first. You need to know the most important concepts (such as the axis argument) before you dive into machine learning and data science. Only then, you can properly understand the algorithms and build your career on a solid foundation. </p>



<p>To help you accomplish this, we&#8217;ve written an easy-to-read, fun introduction into the NumPy library. It&#8217;s 100% based on puzzle-based learning: you solve rated NumPy puzzles, test your skills, and improve over time. Check it out&#8212;it&#8217;s fun! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<figure class="wp-block-image is-resized"><a href="https://blog.finxter.com/coffee-break-numpy/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy_v2-683x1024.png" alt="" class="wp-image-2792" width="342" height="512"/></a></figure>



<h4 class="wp-block-heading">Solution</h4>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>2.75</p>
</blockquote>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-weighted-average-numpy-array-along-axis/">How to Calculate the Weighted Average of a Numpy Array in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Calculate the Average of a NumPy 2D Array?</title>
		<link>https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Sat, 13 Feb 2021 07:42:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[2D array]]></category>
		<category><![CDATA[Average]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[Numpy Array]]></category>
		<category><![CDATA[Python 3]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=473</guid>

					<description><![CDATA[<p>NumPy is a popular Python library for data science focusing on arrays, vectors, and matrices. This article introduces the np.average() function from the NumPy library. When applied to a 1D array, this function returns the average of the array values. When applied to a 2D array, NumPy simply flattens the array. The result is the ... <a title="How to Calculate the Average of a NumPy 2D Array?" class="read-more" href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/" aria-label="Read more about How to Calculate the Average of a NumPy 2D Array?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/">How to Calculate the Average of a NumPy 2D Array?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">NumPy </a>is a popular Python library for data science focusing on arrays, vectors, and matrices. This article introduces the <code>np.average()</code> function from the NumPy library. </p>



<p class="has-pale-cyan-blue-background-color has-background">When applied to a 1D array, this function returns the average of the array values. When applied to a 2D array, NumPy simply flattens the array. The result is the average of the flattened 1D array. Only if you use the optional <code>axis</code> argument, you can average along the rows or columns of the 2D array.</p>



<p>Here&#8217;s a visual overview first&#8212;we&#8217;ll discuss details later:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-1024x576.jpg" alt="NumPy np.average() 2D matrix" class="wp-image-23868" style="width:768px;height:432px" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2021/02/average_numpy-1-768x432.jpg 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p></p>



<p>Let&#8217;s start with the simple, flat case first.</p>



<h2 class="wp-block-heading">Average of Flattened 2D Array</h2>



<p>To calculate the average of all values in a two-dimensional NumPy array called <code>matrix</code>, use the <code>np.average(matrix)</code> 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="">>>> import numpy as np
>>> matrix = np.array([[1, 0, 2],
                       [1, 1, 1]])
>>> np.average(matrix)
1.0</pre>



<p>This calculates the average of the flattened out matrix, i.e., it&#8217;s the same as calling <code>np.average([1, 0, 2, 1, 1, 1])</code> without the two-dimensional structuring of the data. </p>



<h2 class="wp-block-heading">Column Average of 2D Array</h2>



<p>To calculate the average separately for each column of the 2D array, use the function call <code>np.average(matrix, axis=0)</code> setting the axis argument to 0.</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="">>>> np.average(matrix, axis=0)
array([1. , 0.5, 1.5])</pre>



<p>The resulting array has three average values, one per column of the input <code>matrix</code>. </p>



<h2 class="wp-block-heading">Row Average of 2D Array</h2>



<p>To calculate the average separately for each row of the 2D array, call <code>np.average(matrix, axis=1)</code> setting the axis argument to 1. </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="">>>> np.average(matrix, axis=1)
array([1., 1.])</pre>



<p>The resulting array has two average values, one per row of the input <code>matrix</code>.</p>



<h2 class="wp-block-heading">NumPy Puzzle Average</h2>



<p>To test your skills and train your understanding of the np.average() function, here&#8217;s a code puzzle you may enjoy:</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="">import numpy as np

# stock prices (3x per day)
# [morning, midday, evening]
solar_x = np.array(
    [[2, 3, 4], # day 1
     [2, 2, 5]]) # day 2

print(np.average(solar_x))</pre>



<p><em>What is the output of this puzzle?</em><br>*Beginner Level* (solution below)</p>



<p>You can solve this code puzzle interactively on our Finxter.com puzzle app <a href="https://app.finxter.com/learn/computer/science/432" target="_blank" rel="noreferrer noopener" title="https://app.finxter.com/learn/computer/science/432">here</a>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://app.finxter.com/learn/computer/science/432" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="1024" height="653" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-55-1024x653.png" alt="" class="wp-image-23858" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-55-1024x653.png 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/image-55-300x191.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-55-768x490.png 768w, https://blog.finxter.com/wp-content/uploads/2021/02/image-55.png 1270w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>
</div>


<p>The puzzle has a matrix with two rows and three columns. The matrix gives the stock prices of the <code>solar_x</code> stock. Each row represents the prices for one day. The first column specifies the morning price, the second the midday price, and the third the evening price.</p>



<p>Note that NumPy calculates the average as the <a title="Python One Line Sum List" href="https://blog.finxter.com/python-one-line-sum-list/" target="_blank" rel="noreferrer noopener">sum</a> of all values divided by the number of values. The result is a <a title="Python float() Function" href="https://blog.finxter.com/python-float-function/" target="_blank" rel="noreferrer noopener">float </a>value.</p>



<p><br>Are you a master coder?<br><a rel="noopener" href="https://app.finxter.com/learn/computer/science/432" target="_blank">Test your skills now!</a></p>



<p>Note that the following tutorial may be interesting to you too:</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/how-to-get-the-length-of-a-2d-numpy-array/" data-type="post" data-id="781650" target="_blank" rel="noreferrer noopener">How to Get the Length of a 2D NumPy Array</a></p>



<h2 class="wp-block-heading">Related Video</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Statistics: The average | Descriptive statistics | Probability and Statistics | Khan Academy" width="937" height="703" src="https://www.youtube.com/embed/uhxtUt_-GyM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-simple-average-of-numpy-array/">How to Calculate the Average of a NumPy 2D Array?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Calculate the Standard Deviation in NumPy?</title>
		<link>https://blog.finxter.com/how-to-calculate-column-standard-deviation-2d-numpy-array/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 11 Feb 2021 20:01:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[2D array]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[numpy.std]]></category>
		<category><![CDATA[standard deviation]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=456</guid>

					<description><![CDATA[<p>Problem Formulation: How to calculate the standard deviation in NumPy? Differentiations: There are many different variants of this problem: Calculate the standard deviation of a 1D array Calculate the standard deviation of a 2D array Calculate the standard deviation of a 3D array Then you can also calculate the standard deviation along an axis: Calculate ... <a title="How to Calculate the Standard Deviation in NumPy?" class="read-more" href="https://blog.finxter.com/how-to-calculate-column-standard-deviation-2d-numpy-array/" aria-label="Read more about How to Calculate the Standard Deviation in NumPy?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-column-standard-deviation-2d-numpy-array/">How to Calculate the Standard Deviation in NumPy?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><strong>Problem Formulation:</strong> How to calculate the standard deviation in NumPy?</p>



<p><strong>Differentiations</strong>: There are many different variants of this problem:</p>



<ul class="wp-block-list"><li>Calculate the standard deviation of a 1D array</li><li>Calculate the standard deviation of a 2D array</li><li>Calculate the standard deviation of a 3D array</li></ul>



<p>Then you can also calculate the standard deviation along an axis:</p>



<ul class="wp-block-list"><li>Calculate the standard deviation of a 2D array along the columns</li><li>Calculate the standard deviation of a 2D array along the rows</li></ul>



<p>All of them use the <code>np.std(array, axis)</code> function that can be customized to the problem at hand. </p>



<pre class="wp-block-preformatted"><strong>Syntax</strong>: np.std(array, axis=0)</pre>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>Argument</strong></td><td><code>array-like</code></td><td>Array for which the standard deviation should be calculated</td></tr><tr><td><strong>Argument</strong></td><td><code>axis</code></td><td>Axis along which the standard deviation should be calculated. Optional.</td></tr><tr><td><strong>Return Value</strong></td><td><code>array</code> or <code>number</code></td><td>If no axis argument is given (or is set to 0), returns a number. Otherwise returns the standard deviation along the axis which is a NumPy array with a dimensionality reduced by one.</td></tr></tbody></table></figure>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/02/standard_deviation_numpy-1024x576.jpg" alt="How to Calculate the Standard Deviation in NumPy?" class="wp-image-23729" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/standard_deviation_numpy-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/standard_deviation_numpy-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2021/02/standard_deviation_numpy-768x432.jpg 768w" sizes="auto, (max-width: 768px) 100vw, 768px" /></figure></div>



<p>Before we dive into the different ways to calculate the standard deviation in NumPy, let me quickly give you a hint that there are additional optional arguments&#8212;but most of them are little-used. You can check them out <a href="https://numpy.org/doc/stable/reference/generated/numpy.std.html" target="_blank" rel="noreferrer noopener" title="https://numpy.org/doc/stable/reference/generated/numpy.std.html">here</a>. </p>



<p></p>



<h2 class="wp-block-heading">How to calculate the standard deviation of a 1D array</h2>



<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="">import numpy as np

arr = np.array([0, 10, 0])
dev = np.std(arr)

print(dev)
# 4.714045207910316</pre>



<h2 class="wp-block-heading">How to calculate the standard deviation of a 2D array</h2>



<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="">import numpy as np

arr = np.array([[1, 2, 3],
                [1, 1, 1]])
dev = np.std(arr)
print(dev)
# 0.7637626158259734
</pre>



<h2 class="wp-block-heading">How to calculate the standard deviation of a 3D array</h2>



<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="">import numpy as np

arr = np.array([[[1, 1], [0, 0]],
                [[0, 0], [0, 0]]])
dev = np.std(arr)
print(dev)
# 0.4330127018922193</pre>



<p>You can pass an n-dimensional array and NumPy will just calculate the standard deviation of the flattened array. </p>



<h2 class="wp-block-heading">How to calculate the standard deviation of a 2D array along the columns</h2>



<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="">import numpy as np

matrix = [[1, 2, 3],
          [2, 2, 2]]

# calculate standard deviation along columns
y = np.std(matrix, axis=0)
print(y)
# [0.5 0.  0.5]</pre>



<h2 class="wp-block-heading">How to calculate the standard deviation of a 2D array along the rows</h2>



<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="">import numpy as np

matrix = [[1, 2, 3],
          [2, 2, 2]]

# calculate standard deviation along rows
z = np.std(matrix, axis=1)
print(z)
# [0.81649658 0.]</pre>



<h2 class="wp-block-heading">Data Science NumPy Puzzle</h2>



<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="">import numpy as np

# daily stock prices
# [open, close]
google = np.array(
    [[1239, 1258], # day 1
     [1262, 1248], # day 2
     [1181, 1205]]) # day 3

# standard deviation
y = np.std(google, axis=1)

print(y[2] == max(y))</pre>



<p><em>What is the output of this puzzle?</em><br>*Advanced Level*</p>



<p>You can solve the puzzle in our interactive Finxter app here:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://app.finxter.com/learn/computer/science/429" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="1024" height="713" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-52-1024x713.png" alt="NumPy Standard Deviation Puzzle" class="wp-image-23704" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-52-1024x713.png 1024w, https://blog.finxter.com/wp-content/uploads/2021/02/image-52-300x209.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-52-768x535.png 768w, https://blog.finxter.com/wp-content/uploads/2021/02/image-52.png 1263w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure></div>



<p>Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.</p>



<p>This puzzle introduces the standard deviation function of the NumPy library. When applied to a 1D array, this function returns its standard deviation. When applied to a 2D array, NumPy simply flattens the array. The result is the standard deviation of the flattened 1D array.</p>



<p>In the puzzle, we have a matrix with three rows and two columns. The matrix stores the open and close prices of the Google stock for three consecutive days. The first column specifies the opening price, the second the closing price.</p>



<p>We are interested in the standard deviation of the three days. How much does the stock price deviate from the mean between the opening and the closing price?</p>



<p>Numpy provides this functionality via the axis parameter. In a 2D matrix, the row is specified as <code>axis=0</code> and the column as <code>axis=1</code>. We want to compute the standard deviation along the column, i.e., <code>axis=1</code>. This results in three standard deviation values &#8211; one per each day.</p>



<p>Clearly, on the third day, we have observed the highest standard deviation.</p>



<p><br>Are you a master coder?<br><a href="https://app.finxter.com/learn/computer/science/429" target="_blank" rel="noreferrer noopener">Test your skills now!</a></p>



<h2 class="wp-block-heading">Related Video 1</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Calculate Standard Deviation" width="937" height="527" src="https://www.youtube.com/embed/WVx3MYd-Q9w?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Related Video 2</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Standard Deviation part 1: Programming in Python, and Graphing in Matplotlib" width="937" height="527" src="https://www.youtube.com/embed/ZCvdPjxFkrE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>The post <a href="https://blog.finxter.com/how-to-calculate-column-standard-deviation-2d-numpy-array/">How to Calculate the Standard Deviation in NumPy?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Numpy 101: How to Calculate the Row Variance of a Numpy 2D Array?</title>
		<link>https://blog.finxter.com/how-to-calculate-row-variance-numpy-array/</link>
					<comments>https://blog.finxter.com/how-to-calculate-row-variance-numpy-array/#respond</comments>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 27 Sep 2019 08:59:00 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Daily Data Science Puzzle]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[2D array]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[numpy variance]]></category>
		<category><![CDATA[variance]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=444</guid>

					<description><![CDATA[<p>You can play with the following interactive Python code to calculate the variance of a 2D array (total, row, and column variance). Here&#8217;s another practical example: What is the output of this puzzle?*Advanced Level* (solution below) Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices. This puzzle introduces a ... <a title="Python Numpy 101: How to Calculate the Row Variance of a Numpy 2D Array?" class="read-more" href="https://blog.finxter.com/how-to-calculate-row-variance-numpy-array/" aria-label="Read more about Python Numpy 101: How to Calculate the Row Variance of a Numpy 2D Array?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-row-variance-numpy-array/">Python Numpy 101: How to Calculate the Row Variance of a Numpy 2D Array?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You can play with the following interactive Python code to calculate the variance of a 2D array (total, row, and column variance).</p>



<figure><iframe loading="lazy" src="https://repl.it/repls/TroubledThornyBot?lite=true" allowfullscreen="true" width="100%" height="900px"></iframe></figure>



<p>Here&#8217;s another practical example:</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="">import numpy as np

# stock prices (3x per day)
# [morning, midday, evening]
APPLE = np.array(
[[50,60,55], # day 1
[60,60,65]]) # day 2

# midday variance
y = np.var(APPLE, axis=0)[1]

print(int(y))</pre>



<p><em>What is the output of this puzzle?</em><br>*Advanced Level* (solution below)</p>



<p>Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.</p>



<p>This puzzle introduces a new feature of the numpy library: the variance function. When applied to a 1D numpy array, this function returns the variance of the array values. The variance is the average squared deviation from the mean of the values in the array.<br>When applied to a 2D numpy array, numpy simply flattens the array. The result is the variance of the flattened 1D array.</p>



<p>In the puzzle, we have a matrix with two rows and three columns. The matrix gives the stock prices of the Apple stock. Each row represents the prices for one day. The first column specifies the morning price, the second the midday price, and the third the evening price.</p>



<p>Now, we do not want to know the variance of the flattened matrix but the variance of the price in the midday. In both days, the midday price was $60. Therefore, the variance is 0.</p>



<p>Numpy provides this functionality via the axis parameter. In a 2D matrix, the row is specified as axis=0 and the column as axis=1. We want to know three variances, for the morning, midday, and evening. Hence, we calculate the variance along the row, i.e., axis=0. This results in three variance values. Now we take the second element to get the midday variance.</p>



<p><br>Are you a master coder?<br><a href="https://app.finxter.com/learn/computer/science/428">Test your skills now!</a></p>



<h4 class="wp-block-heading">Related Video</h4>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to use Numpy Arrays in Python" width="937" height="527" src="https://www.youtube.com/embed/rnw1qixAv1s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div></figure>



<h4 class="wp-block-heading">Solution</h4>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>0</p></blockquote>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-row-variance-numpy-array/">Python Numpy 101: How to Calculate the Row Variance of a Numpy 2D Array?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.finxter.com/how-to-calculate-row-variance-numpy-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-05-25 12:50:56 by W3 Total Cache
-->