Tutorial – numpy.append() and numpy.concatenate() in Python

numpy.append() and numpy.concatenate() in Python
numpy.append() and numpy.concatenate() in Python

Introduction

While working with your machine learning and data science projects, you will come across instances where you will need to join different numpy arrays for performing an operation on them. This can be done by using numpy append or numpy concatenate functions. In this article, we will learn about numpy.append() and numpy.concatenate() and understand in-depth with some examples.

Importing Numpy Library

Let us commence this article by importing numpy library.

In [1]:
import numpy as np

We’ll begin this article with numpy append function.

Numpy Append : np.append()

The numpy.append() function is used to add items/elements or arrays to an already existing array.

Syntax

numpy.append(arr, values, axis=None)

Ad
Deep Learning Specialization on Coursera

arr : array_like – These are the values are appended to a copy of this array.

values : array_like – These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.

axis : int (optional) – The axis along which values are appended. If the axis is not given, both arr and values are flattened before use.

The result obtained through numpy.append() is a copy of arr with values appended to the axis. This append is not in-place i.e. original array values are not changed, whereas a new array is allocated and filled. If axis is None, out is a flattened array.

Example 1: Appending multiple arrays to an array

Here array a is created and then two arrays are appended to a with the help of np.append(). The resulting array of append function is a copy of the original array with other arrays added to it. The original array is always at the beginning of the resulting array.

In [2]:
a = np.array([1,2,3])
In [3]:
np.append(a, [[4, 5, 6], [7, 8, 9]])
Out[3]:
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Example 2: When axis is specified as ‘0’

This example shows that it is important to take care of the shape of values argument when axis is specified. The array[1,5,7] is appended to 2-D array [[2,5,8],[3,4,7]].

In [4]:
np.array([[2,5,8],[3,4,7]])
Out[4]:
array([[2, 5, 8],
       [3, 4, 7]])
In [5]:
np.array([[1,5,7]])
Out[5]:
array([[1, 5, 7]])
In [6]:
np.append([[2, 5, 8], [3, 4, 7]], [[1, 5, 7]], axis=0)
Out[6]:
array([[2, 5, 8],
       [3, 4, 7],
       [1, 5, 7]])

Example 3 : When axis is specified as ‘0’ but shape of appending array is incorrect

We may encounter an error if the shape of the arrays are not compatible. Here the array[7,8,9] is flattened array which has caused error in appending.

In [7]:
np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-ab6e01c40c40> in <module>
----> 1 np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)

H:\Anaconda\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
   4692         values = ravel(values)
   4693         axis = arr.ndim-1
-> 4694     return concatenate((arr, values), axis=axis)
   4695 
   4696 

ValueError: all the input arrays must have same number of dimensions

Moving onto the next function, we have concatenate function.

Numpy Concatenate : np.concatenate()

Whenever we wish to join two different arrays, then we use numpy concatenate function. Below we will learn about its syntax and arguments used in the function.

Syntax

numpy.concatenate((a1,a2,……), axis=0,out=None)

a1, a2,… : sequence of array_like – These are the arrays used for concatenating with each other. The arrays should have same shape.

axis : int (optional) – The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

out : ndarray (optional) – If provided, this is the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.

After executing this function, we get a concatenated array.

Example 1: With axis as ‘None’

In this example, we will be using axis parameter value as ‘None’, here the arrays will be flattened and then concatenation will be performed.

In [8]:
a = np.array([[5, 2], [8, 4]])
a
Out[8]:
array([[5, 2],
       [8, 4]])
In [9]:
b = np.array([[9, 7]])
b
Out[9]:
array([[9, 7]])
In [10]:
np.concatenate((a, b), axis=None)
Out[10]:
array([5, 2, 8, 4, 9, 7])

Example 2: With axis as ‘0’

When axis is ‘0’ then concatenation operation takes place on the columns. This is the reason array[5,6] is added column-wise to the 2-D Array [[1,2],[3,4]]

In [11]:
np.concatenate((a, b), axis=0)
Out[11]:
array([[5, 2],
       [8, 4],
       [9, 7]])
Example 3: With axis as ‘1’.

Here we have transposed the b array to match the shape of both arrays. When axis is ‘1’ then concatenation operation takes place on the rows. This is the reason array[5,6] is added row-wise to the 2-D Array [[1,2],[3,4]]

In [12]:
# Transposing array 'b'
b.T
Out[12]:
array([[9],
       [7]])

If the array ‘b’ is not transposed, then the shape of concatenating arrays will not match and error will be produced.

In [13]:
np.concatenate((a, b.T), axis=1)
Out[41]:
array([[5, 2, 9],
       [8, 4, 7]])

Conclusion

We have reached the end of this article in which we learned about numpy append and numpy concatenate functions by studying the syntax and different practical usages. Both of these functions are helpful in joining elements/arrays to existing arrays.

 

Reference-  https://numpy.org/doc/

Like and Comment section (Community Members)

Create Your ML Profile!

Don't miss out to join exclusive Machine Learning community

Comments

No comments yet