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:
Code:
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
Code:
vstack
and
Code:
column_stack
helper functions. (ii) the
Code:
numpy.insert
function.

[b]Problem Formulation[/b]

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

Example: Consider the following array –

Code:
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:

Code:
[[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.)

[Image: Cover_Coffee_Break_NumPy-200x300.jpg]

[b]Method 1: Using numpy.append()[/b]
  • Use
    Code:
    numpy.append(given_array, elements_to_be_appended, axis)
    to return an extended array with elements across a specified axis.

  • NumPy’s 
    Code:
    append()
     method appends values to the end of the array. The optional 
    Code:
    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
    Code:
    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
    Code:
    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:

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:

Code:
[[1 2 7] [3 4 8] [5 6 9]]
[b]Method 2: Stacking Elements Along Rows and Columns[/b]
  • Call
    Code:
    np.vstack([given_array, [elements_to_be_stacked]])
    to extend the given array along the row.

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

Note:
  • NumPy’s 
    Code:
    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).

  •  
    Code:
    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:

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:

Code:
[[1 2 7] [3 4 8] [5 6 9]]
[b]Method 3: Using numpy.insert[/b]

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

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

Code:
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
    Code:
    values=[5,6]
    at the third row call the insert method as:
    Code:
    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
    Code:
    axis=0
    indicates that the values will be inserted along the row.

  • To insert the
    Code:
    values=[7, 8, 9]
    at the third column call the insert method as:
    Code:
    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
    Code:
    axis=0
    indicates that the values will be inserted along the column.

[b]Method 4: Concatenate Two 2D Arrays[/b]

Note: NumPy’s 
Code:
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, 
Code:
np.concatenate(a, b, axis=0)
 joins arrays along the first axis and 
Code:
np.concatenate(a, b, axis=None)
 joins the flattened arrays.
  • Call
    Code:
    np.concatenate((arr_a, arr_b), axis=1)
    to concatenate the two given arrays along the columns.

  • Call
    Code:
    np.concatenate((arr_a, arr_b), axis=0)
    to concatenate the two given arrays along the rows.

Code:
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:

Code:
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?

[b]Conclusion[/b]

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

[Image: image-105.png]

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.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: