Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Iterate over a NumPy Array

#1
How to Iterate over a NumPy Array

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;555100&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">In this article, you’ll learn how to iterate over a 1D, 2D and 3D <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array using Python.</p>
<p><em>When</em> <em>working with the <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> library, you will encounter situations where you will need to iterate through a 1D, 2D and even a 3D array. This article will show you how to accomplish this task.</em></p>
<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to iterate through a <em>1D, 2D or 3D</em></em> <em><a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array?</em></p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>
<ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio">
<li><strong>Method 1</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code> </a>loop and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a></li>
<li><strong>Method 2</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/for-else-and-while-else-in-python-a-helpful-guide/" data-type="URL" data-id="https://blog.finxter.com/for-else-and-while-else-in-python-a-helpful-guide/" target="_blank"></a><code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a></code> loop and <a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.nditer.html" data-type="URL" data-id="https://numpy.org/doc/stable/reference/generated/numpy.nditer.html" target="_blank"><code>np.nditer()</code></a></li>
<li><strong>Method 3</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/for-else-and-while-else-in-python-a-helpful-guide/" data-type="URL" data-id="https://blog.finxter.com/for-else-and-while-else-in-python-a-helpful-guide/" target="_blank"></a><code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a></code> loop and <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="URL" data-id="https://blog.finxter.com/iterators-iterables-and-itertools/"><code>itertools</code></a></li>
<li><strong>Method 4</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>While</code></a> loop and <a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html" data-type="URL" data-id="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html" target="_blank"><code>np.size</code></a></li>
<li><strong>Method 5</strong>: Use a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a></code> loop and <a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.ndenumerate.html" data-type="URL" data-id="https://numpy.org/doc/stable/reference/generated/numpy.ndenumerate.html" target="_blank"><code>np.ndenumerate()</code></a></li>
<li><strong>Method 6</strong>: Use a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a></code> Loop and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-range-function/" data-type="URL" data-id="https://blog.finxter.com/python-range-function/" target="_blank"><code>range()</code></a></li>
<li><strong>Bonus</strong>: CSV to <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a></li>
</ul>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Preparation</h2>
<p>Before moving forward, please ensure the <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> library is installed. Click <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-numpy-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-numpy-in-python/" target="_blank">here</a> if you require instructions.</p>
<p>Then, add the following code to the top of each script. This snippet will allow the code in this article to run error-free.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np </pre>
<p>After importing the <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> library, this library is referenced by calling the shortcode (<code>np</code>).</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 1: Use a For Loop and np.array()</h2>
<p class="has-global-color-8-background-color has-background">This method uses a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code> </a>loop combined with <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a> to iterate through a <strong>1D</strong> <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array. The first five (5) <strong>Atomic Numbers </strong>from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee" data-type="URL" data-id="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee" target="_blank" rel="noreferrer noopener">Periodic Table</a> are generated and displayed for this example<a href="https://ptable.com/?lang=en#Properties">.</a></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">atomic_els = np.array(np.arange(1,6)) for el in atomic_els: print(el, end=' ')</pre>
<p>Above, calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a> function and passes it <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-arange/" data-type="URL" data-id="https://blog.finxter.com/numpy-arange/" target="_blank"><code>np.arange(1,6)</code></a> with two (2) arguments: a start position of one (1) and stop position of five (5) or (stop-1). The result is an array<a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods/" data-type="URL" data-id="https://blog.finxter.com/python-list-methods/" target="_blank"> </a>of integers and saves to <code>atomic_els</code>. </p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>[1 2 3 4 5]</code></td>
</tr>
</tbody>
</table>
</figure>
<p>Next, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a> loop is instantiated and iterates through each element of the <strong>1D</strong> <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="URL" data-id="https://blog.finxter.com/numpy-tutorial/" target="_blank"><code><code>atomic_els</code></code></a>. </p>
<p>The output is sent to the terminal on one (1) line as an additional argument was passed to the print statement (<code>end=' '</code>). This argument replaces the default <a href="https://blog.finxter.com/python-regex-match-whitespace-but-not-newline/" data-type="post" data-id="524754" target="_blank" rel="noreferrer noopener">newline character</a> with a blank space.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>1 2 3 4 5</code></td>
</tr>
</tbody>
</table>
</figure>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-iterate-over-a-numpy-array/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fs55BEAJRTOk%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 2: Uses a For Loop and nditer()</h2>
<p class="has-global-color-8-background-color has-background">This method uses a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" target="_blank"></a><code><a rel="noreferrer noopener" href="https://blog.finxter.com/for-else-and-while-else-in-python-a-helpful-guide/" data-type="URL" data-id="https://blog.finxter.com/for-else-and-while-else-in-python-a-helpful-guide/" target="_blank"></a><code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a></code></code> loop combined with <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"></a><code><a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.nditer.html" data-type="URL" data-id="https://numpy.org/doc/stable/reference/generated/numpy.nditer.html" target="_blank"><code>np.nditer()</code></a></code> to iterate through a <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array. The first five (5) <strong>Atomic Numbers</strong> and <strong>Number of Neutrons </strong>data from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a> display for this example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">atomic_data = np.array([np.arange(1,6), [0, 2, 4, 5, 6]]) for dim in atomic_data: for d in dim: print(d, end=' ')</pre>
<p>Above, calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a> function and passes <a rel="noreferrer noopener" href="https://blog.finxter.com/python-range-function/#:~:text=The%20range()%20function%20returns,the%20brilliant%20Carl%20Friedrich%20Gauss." data-type="URL" data-id="https://blog.finxter.com/python-range-function/#:~:text=The%20range()%20function%20returns,the%20brilliant%20Carl%20Friedrich%20Gauss." target="_blank"></a><code><a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-arange/" data-type="URL" data-id="https://blog.finxter.com/numpy-arange/" target="_blank"><code>np.arange(1,6)</code></a></code> as the first argument and an array of associated <strong>Number of <strong>Neutrons</strong></strong> values as the second. </p>
<p>Next, an outer <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop is instantiated. This iterates through each array dimension. </p>
<p>Inside this loop, another <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop is instantiated. The inside loop iterates through each element of the above dimensions.</p>
<p>The output is sent to the terminal on one (1) line as an additional argument is passed to the <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print</a> statement (<code>end=' '</code>). This argument replaces the default newline character with a blank space.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code><mark style="background-color:var(--contrast-3)" class="has-inline-color has-contrast-color">1 2 3 4 5</mark> 0 2 4 5 6</code></td>
</tr>
</tbody>
</table>
</figure>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: The first dimension is highlighted to easily differentiate the dimensions.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-iterate-over-a-numpy-array/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fvcu2Q-6sr-Q%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 3: Use a For Loop and itertools</h2>
<p class="has-global-color-8-background-color has-background">This method uses a <code><code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a></code></code> loop and Python’s built-in <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" target="_blank" rel="noreferrer noopener"><code>itertools</code></a> library to iterate through a <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array. The first three (3) <strong>Atomic Numbers</strong>, <strong>Phase</strong>, and <strong>Group </strong>data from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a> display for this example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,7-8" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import itertools atomic_num = np.arange(1,4)
atomic_phase = ['gas', 'gas', 'solid']
atomic_group = [1, 18, 1] for (a, b, c) in itertools.zip_longest(atomic_num, atomic_phase, atomic_group, fillvalue=0): print (a, b, c)</pre>
<p>Above, imports the <a href="https://blog.finxter.com/iterators-iterables-and-itertools/"><code>itertools</code></a> library to use the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/itertools.html" data-type="URL" data-id="https://docs.python.org/3/library/itertools.html" target="_blank"><code>zip_longest()</code></a> function. </p>
<p>Then, three (3) arrays are declared containing the relevant data for the first three (3) elements from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a>. They save respectively to <code>atomic_num</code>, <code>atomic_phase</code>, and <code>atomic_group</code>.</p>
<p>Next, a <code><code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a></code></code> loop is instantiated and passed three (3) arguments inside the brackets <code>(a, b, c)</code> which reference the arguments inside the <code>zip_longest(atomic_num, atomic_phase, atomic_group)</code> function. </p>
<p>An additional argument (<code>fillvalue=0</code>) is also passed. This fills in any missing values for <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">lists</a> of unequal lengths with the stated value. </p>
<p>The loop <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">iterates</a> until the end of the arrays are reached, outputting to the terminal for each iteration.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>1 gas 1<br />2 gas 18<br />3 solid 1</code></td>
</tr>
</tbody>
</table>
</figure>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-iterate-over-a-numpy-array/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYyliq2-hVDw%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 4: Use a While Loop and Size</h2>
<p class="has-global-color-8-background-color has-background">This method uses a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>while</code></a> loop combined with <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"></a><code><code><a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html" data-type="URL" data-id="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html" target="_blank"><code>np.size</code></a></code></code> to iterate through a <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array. The first five (5) <strong>Atomic Numbers</strong>, <strong>Number of Neutrons</strong>, and<strong> Phase </strong>data from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a> display for this example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4-6" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">atomic_names = np.array(['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron'])
el_count = 0 while el_count &lt; atomic_names.size: print(atomic_names[el_count], end=' ') el_count += 1</pre>
<p>Above, calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a> function and passes a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">list</a> containing the first five (5) element names of the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a>. These results save to <code>atomic_names</code>.</p>
<p>Then, a variable, <code>el_count</code>, is declared with a start value of zero (<code>0</code>). This will be a <a href="https://blog.finxter.com/for-loop-with-two-variables-for-i-j-in-python/" data-type="post" data-id="528311" target="_blank" rel="noreferrer noopener">counter</a> variable and lets the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>While</code></a> loop know when to stop iterating.</p>
<p>Next, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>while</code></a> loop is instantiated and iterates through the elements of <code>atomic_names</code>. This will continue while the value of <code>el_count </code>remains less than the value of <code>atomic_names.size</code>.</p>
<p>The output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (<code>end=' '</code>). This argument replaces the default newline character with a blank space.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>Hydrogen Helium Lithium Beryllium Boron</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 5: Use a For Loop and np.ndenumerate()</h2>
<p class="has-global-color-8-background-color has-background">This method uses a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>For</code></a></code> loop and <a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.ndenumerate.html" data-type="URL" data-id="https://numpy.org/doc/stable/reference/generated/numpy.ndenumerate.html" target="_blank"><code>np.ndenumerate()</code></a> to iterate through a <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array. The first five (5) <strong>Element Names</strong> from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a> display for this example. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">atomic_names = np.array(['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron']) for idx, x in np.ndenumerate(atomic_names): print(idx, x)</pre>
<p>Above, calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a> function and passes it an array containing the first five (5) element names from the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a>. The results save to <code>atomic_names</code>.</p>
<p>Next, a <code><code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a></code></code> loop is instantiated referencing <code>idx</code> which is the index of the array, and <code>x</code>, which is the array element’s value. </p>
<p>The output is sent to the terminal. Then <code>idx</code> displays a <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="URL" data-id="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank"><code>Tuple</code></a> containing the index value of the array and then the value of <code>x</code> for each iteration.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>(0,) Hydrogen<br />(1,) Helium<br />(2,) Lithium<br />(3,) Beryllium<br />(4,) Boron</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 6: Use a For Loop and range()</h2>
<p class="has-global-color-8-background-color has-background">This method uses a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a></code> loop and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-range-function/" data-type="URL" data-id="https://blog.finxter.com/python-range-function/" target="_blank"><code>range()</code></a>) to iterate through a 3D <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="7-10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">nums = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]], [[19, 20], [21, 22], [23, 23]], [[24, 25], [26, 27], [28, 29]]]) for x in range(0, 5): for y in range(0, 3): for z in range(0, 2): print(nums[x][y][z])</pre>
<p>Above declares a <strong>3D</strong> <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array containing consecutive numbers from 1-29 inclusive. These save to <code>nums</code>.</p>
<p>Next, three (3) <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a></code> loops are instantiated to loop through and output the contents of <code>nums</code> to the terminal one (1) number per line.</p>
<p>The range() function for each loop is based on the dimensions of the 3D Numpy array, for example:</p>
<ul>
<li>The first loop (<code>range(0,5</code>) identifies the total number of tows in the array.</li>
</ul>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="431" height="153" src="https://blog.finxter.com/wp-content/uploads/2022/08/kath-01aa.png" alt="" class="wp-image-562841" srcset="https://blog.finxter.com/wp-content/uploads/2022/08/kath-01aa.png 431w, https://blog.finxter.com/wp-content/uplo...00x106.png 300w" sizes="(max-width: 431px) 100vw, 431px" /></figure>
</div>
<ul>
<li>The next loop (<code>range(0,3</code>) identifies the number of columns in the array.</li>
</ul>
<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/08/kath-01b.png" alt="" class="wp-image-562855" width="466" height="165" srcset="https://blog.finxter.com/wp-content/uploads/2022/08/kath-01b.png 431w, https://blog.finxter.com/wp-content/uplo...00x106.png 300w" sizes="(max-width: 466px) 100vw, 466px" /></figure>
</div>
<ul>
<li>The final loop (<code>range(0,2</code>) identifies the elements in each column in the array.</li>
</ul>
<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/08/kath-01bb.png" alt="" class="wp-image-562865" width="477" height="169" srcset="https://blog.finxter.com/wp-content/uploads/2022/08/kath-01bb.png 431w, https://blog.finxter.com/wp-content/uplo...00x106.png 300w" sizes="(max-width: 477px) 100vw, 477px" /></figure>
</div>
<p>Finally, the output is sent to the terminal (snippet only).</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />...</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Bonus: Convert CSV to np.array()</h2>
<p class="has-global-color-8-background-color has-background">This example reads in a snippet of the <a href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee">Periodic Table</a> as a <a href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="post" data-id="440655" target="_blank" rel="noreferrer noopener">CSV file</a>. This data is converted to a <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array and is output to the terminal.</p>
<p>The CSV file below contains the values of the <strong>Atomic Number</strong>, <strong>Atomic Mass</strong>, <strong>Number of Neutrons</strong>, and the <strong>Number of Electrons</strong> for the first seven (7) elements from the <a rel="noreferrer noopener" href="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee" data-type="URL" data-id="https://gist.github.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee" target="_blank">Periodic Table</a>.</p>
<p><strong>Contents of <code>pt_sample.csv</code></strong></p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>1,1.007,0<br />2,4.002,2<br />3,6.941,4<br />4,9.012,5<br />5,10.811,6<br />6,12.011,6<br />7,14.007,7</code></td>
</tr>
</tbody>
</table>
</figure>
<p>To follow along, save this file as <code>pt_sample.csv</code> and move it into the current working directory.</p>
<p>Before moving forward, please ensure the <a href="https://blog.finxter.com/category/pandas-library/" data-type="URL" data-id="https://blog.finxter.com/category/pandas-library/" target="_blank" rel="noreferrer noopener">Pandas</a> library is installed. Click <a href="https://blog.finxter.com/how-to-install-pandas-in-python" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python" target="_blank" rel="noreferrer noopener">here</a> if you require instructions.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
import csv file_name = 'pt_sample.csv'
df_data = np.array(list(csv.reader(open(file_name, 'r'), delimiter=','))).astype("float")
print(df_data)</pre>
<p>Above, imports the <a rel="noreferrer noopener" href="https://blog.finxter.com/category/pandas-library/" data-type="URL" data-id="https://blog.finxter.com/category/pandas-library/" target="_blank">Pandas</a> library and the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/csv.html" data-type="URL" data-id="https://docs.python.org/3/library/csv.html" target="_blank">CSV</a> library. This is needed to work with DataFrames and read in the CSV file.</p>
<p>Then, a filename is declared and saves to <code>file_name</code>.</p>
<p>On the highlighted line, the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a> function is called and passed the following arguments.</p>
<ul>
<li>The <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-convert-csv-to-_-8-different-target-formats/" data-type="post" data-id="503412" target="_blank">csv.reader()</a></code> function is passed as an argument and this argument passes the <code>open()</code> method to open the specified CSV file in read (<code>r</code>) mode, including the <code>field</code> delimiter (<code>csv.reader(open(file_name, 'r'), delimiter=',')</code>).</li>
<li>The contents of the CSV file converts to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">list</a>.</li>
<li>This <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">list</a> converts to an <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" data-type="URL" data-id="https://blog.finxter.com/how-to-initialize-a-numpy-array-6-easy-ways/" target="_blank"><code>np.array()</code></a>.</li>
</ul>
<p>The results save to <code>df_data</code> and output to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>[[ 1. 1.007 0. ]<br />[ 2. 4.002 2. ]<br />[ 3. 6.941 4. ]<br />[ 4. 9.012 5. ]<br />[ 5. 10.811 6. ]<br />[ 6. 12.011 6. ]<br />[ 7. 14.007 7. ]]</code></td>
</tr>
</tbody>
</table>
</figure>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-iterate-over-a-numpy-array/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-JKVy_HliQE%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio" id="block-323ff1c3-82fc-4193-9c8d-125f5d3c2efb">Summary</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio" id="block-ebf714b3-b2f5-494e-bcd5-0cd3b3709ed7">These seven (7) methods of iterating a <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy</a> array should give you enough information to select the best one for your coding requirements.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio" id="block-7790db1b-2ed9-424b-885a-382987e3d867">Good Luck &amp; Happy Coding!</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Programmer Humor – Blockchain</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uplo...13x300.png 213w" sizes="(max-width: 280px) 100vw, 280px" /><figcaption><em>“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.”</em> <strong>source </strong> – <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/08/...mpy-array/
Reply



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016