numpy.append() in Python


The numpy.append() function in Python is used to add values to the end of the array and returns the new array. Dimensions of the input array must be matched otherwise ValueError will be generated.

Basic Syntax

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

And following are the parameters:

Parameter Description
array specify the input array
values These values will be appended at the end of the array. The shape must be the same.
axis axis=0 for column and axis = 1 for row. if not specified array will be flattened

Return value

This function will return the appended array with provided values through it.

Example

Following are examples for numpy.append() function.

Example 1: Following is an example for numpy.append() function

# Python Program for numpy.append() 

import numpy as np 

# first 1D array
items1 = np.arange(4) 
print("First Array : ", items1) 


# second 1D array
items2 = np.arange(8, 10) 
print("\nSecond Array : ", items2) 


# combining 1st and 2nd array 
items3 = np.append(items1, items2) 
print("\n Third array : ", items3) 

The output should be:

First Array : [0, 1, 2, 3]
Second Array : [8, 9])
Third array : [0, 1, 2, 3, 8, 9]

Example 2: Following is an another example for numpy.append() function

#Python program for numpy.append() function
import numpy as np 

items = np.array([[0,1,2,3,4],[5,6,7,8,9]]) 

print 'Initial items array:' 
print items

print '\nAppend all given elements to items array:' 
print np.append(items, [10,11,12,13,14]) 

print '\nAppend all given elements to items array along axis 0:' 
print np.append(items, [[10,11,12,13,14]],axis = 0) 

print '\nAppend all given elements to items array along axis 1:' 
print np.append(items, [[10,11,12,13,14],[15,16,17,18,19]],axis = 1)

The output should be:

Initial items array:
[[0 1 2 3 4]
[5 6 7 8 9]]
Append all given elements to items array:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
Append all given elements to items array along axis 0:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Append all given elements to items array along axis 1:
[[ 0 1 2 3 4 10 11 12 13 14]
[ 5 6 7 8 9 15 16 17 18 19]]