NumPy – append

NumPy - append

In this chapter, we will discuss about NumPy – append. This function adds values at the end of an input array. The append operation is not in place, a new array is allocated. Also, the dimensions of the input arrays must match otherwise ValueError will be generated.

The function takes the following parameters.

numpy.append(arr, values, axis)

Where,

Sr.No.Parameter & Description
1arrInput array
2values to be appended to arr. It must be of the same shape as of arr (excluding axis of appending)
3axisThe axis along which append operation is to be done. If not given, both parameters are flattened

Example Of NumPy append

import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 

print 'First array:' 
print a 
print '\n'  

print 'Append elements to array:' 
print np.append(a, [7,8,9]) 
print '\n'  

print 'Append elements along axis 0:' 
print np.append(a, [[7,8,9]],axis = 0) 
print '\n'  

print 'Append elements along axis 1:' 
print np.append(a, [[5,5,5],[7,8,9]],axis = 1)

Its output would be as follows −

First array:
[[1 2 3]
 [4 5 6]]

Append elements to array:
[1 2 3 4 5 6 7 8 9]

Append elements along axis 0:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Append elements along axis 1:
[[1 2 3 5 5 5]
 [4 5 6 7 8 9]]

Next Topic – Click Here

This Post Has 2 Comments

Leave a Reply