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

Rate this post

Summary: Call the append function of the Numpy library as: numpy.append(given_array, elements_to_be_appended, axis) to extend the given array along a specific axis.

Other ways of extending the array include using: (i) the vstack and column_stack helper functions. (ii) the numpy.insert function.


Problem Formulation


Given a Numpy array; How will you extend the given array with values along rows and columns?

Example: Consider the following array –

import numpy as np arr = np.array([[1, 2], [3, 4]])
print(arr)

Question: How will you add an extra row and column to the array such that the expected output is:

[[1 2 7] [3 4 8] [5 6 9]]

Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy

Method 1: Using numpy.append()


  • Use numpy.append(given_array, elements_to_be_appended, axis) to return an extended array with elements across a specified axis.
  • NumPy’s append() method appends values to the end of the array. The optional axis 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.

Explanation:

  • To extend the given array across a row call the numpy.append() 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 0.
  • To extend the given array across a column call the numpy.append() 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 1.

Code:

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)

Output:

[[1 2 7] [3 4 8] [5 6 9]]

Method 2: Stacking Elements Along Rows and Columns


  • Call np.vstack([given_array, [elements_to_be_stacked]]) to extend the given array along the row.
  • Call np.column_stack([given_array, [elements_to_be_stacked]]) to extend the given array along the column.

Note:

  • NumPy’s vstack() 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 (N,) to (1,N).
  •  numpy.column_stack() method stacks 1-D arrays as columns into a 2D array. It takes a tuple argument and stacks the arrays in sequence (column wise).

Code:

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)

Output:

[[1 2 7] [3 4 8] [5 6 9]]

Method 3: Using numpy.insert


The numpy.insert() function is used to insert values in a numpy array along a given axis.

Call the np.insert() 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 axis=0, values will be inserted along the rows and when axis=1 values will be inserted along the columns.

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)

Explanation:

  • To insert the values=[5,6] at the third row call the insert method as: np.insert(arr, 2, values=[5, 6], axis=0). The second attribute (i.e. the vaule 2) ensures that the values will be inserted at column index 2 and the axis=0 indicates that the values will be inserted along the row.
  • To insert the values=[7, 8, 9] at the third column call the insert method as: np.insert(arr, 2, values=[7, 8, 9], axis=1). The second attribute (i.e. the vaule 2) ensures that the values will be inserted at row index 2 and the axis=0 indicates that the values will be inserted along the column.

Method 4: Concatenate Two 2D Arrays


Note: NumPy’s concatenate() 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, np.concatenate(a, b, axis=0) joins arrays along the first axis and np.concatenate(a, b, axis=None) joins the flattened arrays.

  • Call np.concatenate((arr_a, arr_b), axis=1) to concatenate the two given arrays along the columns.
  • Call np.concatenate((arr_a, arr_b), axis=0) to concatenate the two given arrays along the rows.
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)

Output:

merge across columns: [[1 2 5 6] [3 4 7 8]]
merge across rows: [[1 2] [3 4] [5 6] [7 8]]

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: How to Concatenate Two NumPy Arrays?

Conclusion


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 subscribe and stay tuned for more interesting tutorials and discussions.

Recommended Tutorials:


Web Scraping with BeautifulSoup


One of the most sought-after skills on Fiverr and Upwork is web scraping . Make no mistake: extracting data programmatically from websites 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 Python’s BeautifulSoup library for web scraping.



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



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Library Hijacking – A Simple Demonstration on NumPy xSicKxBot 0 1,252 11-22-2022, 01:48 AM
Last Post: xSicKxBot
  [Tut] Solidity Bytes and String Arrays, Concat, Allocating Memory, and Array Literals xSicKxBot 0 1,204 10-25-2022, 09:13 AM
Last Post: xSicKxBot
  [Tut] How to Convert Pandas DataFrame/Series to NumPy Array? xSicKxBot 0 1,218 10-24-2022, 02:13 PM
Last Post: xSicKxBot
  [Tut] How to Print a NumPy Array Without Scientific Notation in Python xSicKxBot 0 1,220 10-20-2022, 11:44 AM
Last Post: xSicKxBot
  [Tut] Python – Return NumPy Array From Function xSicKxBot 0 1,191 10-16-2022, 03:49 AM
Last Post: xSicKxBot
  [Tut] How to Find the Longest String in a NumPy Array? xSicKxBot 0 1,101 09-19-2022, 11:34 AM
Last Post: xSicKxBot
  [Tut] Combine Images Using Numpy xSicKxBot 0 1,219 09-18-2022, 10:23 AM
Last Post: xSicKxBot
  [Tut] How to Iterate over a NumPy Array xSicKxBot 0 1,159 08-19-2022, 06:55 PM
Last Post: xSicKxBot
  [Tut] How to Convert a CSV to NumPy Array in Python? xSicKxBot 0 1,176 07-11-2022, 03:42 AM
Last Post: xSicKxBot
  [Tut] How to Call an Element from a Numpy Array? xSicKxBot 0 1,160 06-21-2022, 04:08 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:

Forum software by © MyBB Theme © iAndrew 2016