Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy Append() Method



The Numpy Append() method adds values to the end of an input array, allocating a new array for the result rather than modifying the original in place.

If no axis is specified then both the array and values are flattened before appending. When an axis is specified then the dimensions of the input arrays must match otherwise ValueError will be raised.

Syntax

Following is the syntax of the Numpy append() method −

numpy.append(arr, values, axis)

Parameters

Below are the parameters of the Numpy append() method −

  • arr: Input Array
  • values: These are the values to be appended to input array. It must be of the same shape as of the input array 'arr'(excluding axis of appending)
  • axis: The axis along which append operation is to be done. If not given then both parameters are flattened

Return value

This method returns a new array which includes the original array along with the specified values appended.

Example

Following is the example of appending elements into the array using Numpy append() method −

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))

Output

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]]
numpy_array_manipulation.htm
Advertisements