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)
[[1 2]
[3 4]]
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.)
Video Explanation
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 optionalaxis
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 theaxis=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 theaxis=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:
- NumPy Tutorial – Everything You Need to Know to Get Started
- [Collection] 10 Best NumPy Cheat Sheets Every Python Coder Must Own
- How to Index Elements in NumPy Arrays?
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.