NumPy – Arithmetic, Indexing, Shape Manipulation

This page covers NumPy’s basic operations – Array Arithmetic, Array Indexing and Slicing, and Array Shape Manipulation.  These operations constitute the basic building blocks in developing programs for scientific applications, linear algebra, and machine learning.

This page is under construction.

Arithmetic Operations

NumPy provides a powerful way to perform arithmetic operations on arrays. You can perform arithmetic operations like addition, subtraction, multiplication, and division on arrays. In NumPy, arithmetic operators apply elementwise. meaning each element in one array is operated on by the corresponding element in another array.

These operations can also be performed between an array and a single number. The single number applies the operation to every element in the array.

The operation returns a new array filled with the result.

Array Addition and Subtraction

In the following examples, “arr1” and “arr2” are the two arrays to be operated on.

Sum: Sums corresponding elements of two arrays.

Syntax: np.add(arr1, arr2)

Difference: Subtracts elements of the second array from the first.

Syntax: np.subtract(arr1, arr2)

Program Example : NumPy add and subtract

Multiplication an Array by a Scalar

The product operator (*) applies elementwise in NumPy arrays.

Program Example: Multiplication of an Array by a Scalar

Array Multiplication of two arrays

The Multiply operator multiplies corresponding elements of two arrays.

Program Example: Multiplication of Two Arrays

Array Division of two arrays

Divide operator divides elements of the first array by the corresponding elements of the second. Array.

Syntax:

np.divide(arr1, arr2)

Program Example Array Division

Modulo

Modulo operator returns the remainder of the division of the corresponding elements of the two arrays.

Syntax:

np.mod(arr1, arr2)

Program Example Array Division (Remainder)

Exponentiation

Power: Raises elements of the first array to the power of the second array.

Syntax:

np.power(arr1, arr2)

Program Example Array Exponentiation

Unary Operation

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class.

sum

min

max

Indexing, Slicing, and Iterating

One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.

Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas:

Program Example: Indexing in NumPy Arrays

Array Shape Manipulation

An array’s shape is given by the number of elements in each axis.

For example, a 2D array with “m” rows, and “n” columns has shape (m, n).

See program example below.

The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array:

For more details, click the following link:

https://numpy.org/doc/stable/reference/routines.array-manipulation.html

In the following sections, the name of the array is assumed to be ‘a’.

Reshape function reshape()

The NumPy reshape() function changes the shape of an array without altering its data. Note that the total of elements in the new shape remain the same as in the original array.

The Syntax of the reshape() function is:

numpy.reshape(a/shapeorder=’C’*copy=None)

ParameterDescriptionReturns
aArray to be shaped reshaped_array : ndarray  
shapeNew shape specified in Int or tuple of int# of elements in the new array must be same as in the original array 
orderoptional  
copyOptional  

The program below uses the reshape() function to change the shape of an array without altering the data.

Program Example reshape() Function

numpy.ravel() Function

NumPy’s ravel function is used to flatten a multi-dimensional array into a one-dimensional array. The function is useful in memory usage efficiency.

Syntax:

numpy.ravel(aorder=’C’)

Table

ParameterDescriptionReturns
aArray to be flattenedThe elements in a are read in the order specified by order, and packed as a 1-D array Contiguous 1-D array of the same subtype as a
orderOptionalThis specifies the order in which the array elements are read.  

The program below flattens a two-dimensional array.

 Program Example ravel() Function

Transpose Function

The NumPy transpose() function is used to change the orientation of an array by reversing its axes, effectively switching rows with columns in a 2D array.

This function is used in data manipulation and linear algebra.

For more details, click on the link.

https://numpy.org/doc/stable/reference/generated/numpy.transpose.html

Syntax: numpy.transpose(aaxes=None)

ParameterDescriptionReturns
aInput array to be transposed.The elements in a are read in the order specified by order, and packed as a 1-D arrayReturns an array with axes transposed.  
AxesOptional tuple or a list of ints  Specifies the order of the axes. If not provided, the default behavior reverses the dimensions. 

The program example switches the rows and columns of 2×4 2D array.

Program Example Transpose Function

resize() Method

The NumPy resize() function creates a new array with a specified shape and size.

The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself.  See the program below.

Syntax:

Numpy.resize(a, newshape))

ParametersDescriptionReturns
a:  is the array to be resizedThe new array is formed from the data in the old array.Reshaped array: ndarray
newshape: shape of the resized array int or tuple (int)  

For more exploration, click the link below.

https://numpy.org/doc/stable/reference/generated/numpy.resize.html

The following program example of resize() function. The function changes a (2,6) 2-D array to

(6,2) array.  Note that the original array itself has been modified, as opposed to reshape() function that does not change the original array.

Program Example resize() Function

Stacking Together Different Arrays

NumPy allows you to stack several arrays together vertically or horizontally.

Vertical Stack numpy.vstack()

Numpy.vstack() function stacks arrays in sequence vertically (row wise).

The numpy.vstack() function is used to stack arrays vertically, meaning it combines them on top of each other. It requires that the arrays have the same number of columns to work properly.

Syntax:

numpy.vstack(tup*dtype=Nonecasting=’same_kind’)

ParameterDescriptionNotesReturns
tup : sequence of ndarraysA tuple of arrays to be stacked vertically.The arrays must have the same shape along all but the first axis. 1 
dtype : str or dtypeOptional  
castingOptional  

For more details, click the link below:

https://numpy.org/doc/stable/reference/generated/numpy.vstack.html

The following program is an example of stacking two 2D arrays vertically.

Program Example Vertical Stack

Horizontal Stack:  numpy.hstack() Function

The numpy.hstack() function is used to horizontally stack arrays in NumPy, meaning it combines them side by side along the second axis (columns). This function requires that the arrays have the same number of rows to be concatenated successfully.

Syntax:

numpy.hstack(tup*dtype=Nonecasting=’same_kind’)

ParameterDescriptionReturns
tup : sequence of ndarraystup: A tuple or list of arrays to be stacked. All arrays must have the same shape except along the axis being concatenated.The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length. 
dtype : str or dtypeOptional  
castingOptional  

The following program is an example of stacking two 2D arrays horizontally.

Program Example Horizontal Stack

Verified by MonsterInsights