Create an account


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

#1
How to Extend a NumPy Array in Python

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;413229&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&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;}">
<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"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p class="has-global-color-8-background-color has-background"><strong>Summary: </strong>Call the append function of the Numpy library as: <code>numpy.append(given_array, elements_to_be_appended, axis)</code> to extend the given array along a specific axis. </p>
<p>Other ways of extending the array include using: (i) the <code>vstack</code> and <code>column_stack</code> helper functions. (ii) the <code>numpy.insert</code> function.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2><strong>Problem Formulation</strong></h2>
<p>Given a Numpy array; How will you extend the given array with values along rows and columns?</p>
<p><strong>Example: </strong>Consider the following array – </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 arr = np.array([[1, 2], [3, 4]])
print(arr)</pre>
<p><strong>Question: </strong>How will you add an extra row and column to the array such that the <strong>expected output</strong> is:</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="">[[1 2 7] [3 4 8] [5 6 9]]</pre>
<p><strong>Do you want to become a NumPy master?</strong> Check out our interactive puzzle book <a href="https://amzn.to/39dEykm" target="_blank" rel="noreferrer noopener" title="https://amzn.to/39dEykm"><strong>Coffee Break NumPy</strong></a> and boost your data science skills! <em>(Amazon link opens in new tab.)</em></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium"><a href="https://amzn.to/39dEykm" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="200" height="300" src="https://blog.finxter.com/wp-content/uploads/2019/04/Cover_Coffee_Break_NumPy-200x300.jpg" alt="Coffee Break NumPy" class="wp-image-2766"/></a></figure>
</div>
<h2><strong>Method 1:</strong> Using numpy.append()</h2>
<ul class="has-global-color-8-background-color has-background">
<li>Use <code>numpy.append(given_array, elements_to_be_appended, axis)</code> to return an extended&nbsp;array&nbsp;with&nbsp;elements&nbsp;across a specified&nbsp;axis. </li>
<li>NumPy’s&nbsp;<code><a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.append.html" target="_blank">append()</a></code>&nbsp;method appends values to the end of the array. The optional&nbsp;<code>axis</code>&nbsp;argument allows you to append arrays along the specified axis. When the value of axis is 0, elements will be appended across rows and when the value of axis is 1, elements will be appended across columns.</li>
</ul>
<p><strong>Explanation:</strong></p>
<ul>
<li>To extend the given array across a row call the <code>numpy.append()</code> method and pass the given array as an input followed by the row elements to be added to the existing array. Finally, to specify that you want to append the values to a row feed in the value of axis as <strong>0</strong>.</li>
<li>To extend the given array across a column call the <code>numpy.append()</code> method and pass the given array as an input followed by the column elements to be added to the existing array. Finally, to specify that you want to append the values to a column feed in the value of axis as <strong>1</strong>.</li>
</ul>
<p><strong>Code</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="7,5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np arr = np.array([[1, 2], [3, 4]])
# add elements row-wise
arr = np.append(arr, [[5, 6]], 0)
# add elements column-wise
arr = np.append(arr, [[7], [8], [9]], 1)
print(arr)</pre>
<p><strong>Output:</strong></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="">[[1 2 7] [3 4 8] [5 6 9]]</pre>
<h2><strong>Method 2:</strong> Stacking Elements Along Rows and Columns</h2>
<ul class="has-global-color-8-background-color has-background">
<li>Call <code>np.vstack([given_array, [elements_to_be_stacked]])</code> to extend the given array along the row. </li>
<li>Call <code>np.column_stack([given_array, [elements_to_be_stacked]])</code> to extend the given array along the column.</li>
</ul>
<p><strong>Note:</strong></p>
<ul>
<li>NumPy’s&nbsp;<code>vstack()</code>&nbsp;method takes a tuple argument and stacks the arrays in sequence vertically (row wise). This is like concatenating along the first axis after reshaping 1-D arrays of shape&nbsp;<em>(N,)</em>&nbsp;to&nbsp;<em>(1,N)</em>.</li>
<li>&nbsp;<code>numpy.column_stack()</code>&nbsp;method stacks 1-D arrays as columns into a 2D array. It takes a tuple argument and stacks the arrays in sequence (column wise).</li>
</ul>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="5, 7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np arr = np.array([[1, 2], [3, 4]])
# add elements row-wise
arr = np.vstack([arr, [5, 6]])
# add elements column-wise
arr = np.column_stack([arr, [7, 8, 9]])
print(arr)</pre>
<p><strong>Output:</strong></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="">[[1 2 7] [3 4 8] [5 6 9]]</pre>
<h2><strong>Method 3:</strong> Using numpy.insert</h2>
<p>The <code>numpy.insert()</code> function is used to insert values in a numpy array along a given axis. </p>
<p class="has-global-color-8-background-color has-background">Call the <code>np.insert()</code> method and feed in the following parameters: (i) the given array, (ii) the column or the row number before which you want to insert the values, (iii) the values that you want to insert in the array, (iv) the axis along which you want to insert the values. When <code>axis=0</code>, values will be inserted along the rows and when <code>axis=1</code> values will be inserted along the 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="">import numpy as np arr = np.array([[1, 2], [3, 4]])
# add elements row-wise (insert before row 2)
arr = np.insert(arr, 2, values=[5, 6], axis=0)
# add elements column-wise (insert before column 2)
arr = np.insert(arr, 2, values=[7, 8, 9], axis=1)
print(arr)</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>To insert the <code>values=[5,6]</code> at the third row call the insert method as: <code>np.insert(arr, 2, values=[5, 6], axis=0)</code>. The second attribute (i.e. the vaule 2) ensures that the values will be inserted at column index 2 and the <code>axis=0</code> indicates that the values will be inserted along the row.</li>
<li>To insert the <code>values=[7, 8, 9]</code> at the third column call the insert method as: <code>np.insert(arr, 2, values=[7, 8, 9], axis=1)</code>. The second attribute (i.e. the vaule 2) ensures that the values will be inserted at row index 2 and the <code>axis=0</code> indicates that the values will be inserted along the column.</li>
</ul>
<h2><strong>Method 4:</strong> Concatenate Two 2D Arrays</h2>
<p><strong>Note: </strong>NumPy’s&nbsp;<code><a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" target="_blank">concatenate()</a></code>&nbsp;method joins a sequence of arrays along an existing axis. The first couple of comma-separated array arguments are joined. If you use the axis argument, you can specify along which axis the arrays should be joined. For example,&nbsp;<code>np.concatenate(a, b, axis=0)</code>&nbsp;joins arrays along the first axis and&nbsp;<code>np.concatenate(a, b, axis=None)</code>&nbsp;joins the flattened arrays.</p>
<ul class="has-global-color-8-background-color has-background">
<li>Call <code>np.concatenate((arr_a, arr_b), axis=1)</code> to concatenate the two given arrays along the columns.</li>
<li>Call <code>np.concatenate((arr_a, arr_b), axis=0)</code> to concatenate the two given arrays along the rows.</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="">import numpy as np arr_a = np.array([[1, 2], [3, 4]])
arr_b = np.array([[5, 6], [7, 8]])
print('merge across columns: ')
arr = np.concatenate((arr_a, arr_b), axis=1)
print(arr)
print('merge across rows: ')
arr = np.concatenate((arr_a, arr_b), axis=0)
print(arr)</pre>
<p><strong>Output:</strong></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="">merge across columns: [[1 2 5 6] [3 4 7 8]]
merge across rows: [[1 2] [3 4] [5 6] [7 8]]</pre>
<p>There are other ways of merging two given arrays which include approaches that we already learned above. To explore more on this feel free to read the following tutorial: <strong><a href="https://blog.finxter.com/how-to-concatenate-two-numpy-arrays/" target="_blank" rel="noreferrer noopener">How to Concatenate Two NumPy Arrays?</a></strong></p>
<h2><strong>Conclusion</strong></h2>
<p>We have learned as many as four ways of extending a given array in this article. Feel free to use the option that suits your requirements. I hope this article helped you. Please <strong><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">subscribe</a></strong> and stay tuned for more interesting tutorials and discussions. </p>
<p><strong>Recommended Tutorials:</strong></p>
<ul class="has-base-background-color has-background">
<li><strong><a href="https://blog.finxter.com/numpy-tutorial/">NumPy Tutorial – Everything You Need to Know to Get Started</a></strong></li>
<li><strong><a href="https://blog.finxter.com/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own/" target="_blank" rel="noreferrer noopener">[Collection] 10 Best NumPy Cheat Sheets Every Python Coder Must Own</a></strong></li>
<li><strong><a href="https://blog.finxter.com/how-to-index-elements-numpy-arrays/" target="_blank" rel="noreferrer noopener">How to Index Elements in NumPy Arrays?</a></strong></li>
</ul>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p class="has-text-align-center has-base-3-background-color has-background"><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/"><strong>Web Scraping with BeautifulSoup</strong></a></p>
<figure class="wp-block-image is-style-default"><a href="https://academy.finxter.com/university/web-scraping-with-beautifulsoup/"><img loading="lazy" width="928" height="367" src="https://blog.finxter.com/wp-content/uploads/2022/03/image-105.png" alt="" class="wp-image-238589" srcset="https://blog.finxter.com/wp-content/uploads/2022/03/image-105.png 928w, https://blog.finxter.com/wp-content/uplo...00x119.png 300w, https://blog.finxter.com/wp-content/uplo...68x304.png 768w" sizes="(max-width: 928px) 100vw, 928px" /></a></figure>
<p>One of the most sought-after skills on Fiverr and Upwork is&nbsp;<strong>web scraping&nbsp;</strong>. Make no mistake:&nbsp;<em><strong>extracting data programmatically from websites&nbsp;</strong></em>is a critical life-skill in today’s world that’s shaped by the web and remote work. This course teaches you the ins and outs of&nbsp;<em><strong>Python’s BeautifulSoup library&nbsp;</strong></em>for web scraping.</p>
</div>


https://www.sickgaming.net/blog/2022/06/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016