





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.Numpy operations and functions are implemented internally in C++, which makes them much faster than using Python statements & loops that are interpreted at runtime The 5 function's which will be illustrated are as follows,
-function 1 -- np.multiply
-function 2 -- np.matmul
-function 3 -- np.arange
-function 4 -- np.concatenate
-function 5 -- np.stack
!pip install jovian --upgrade -q
import jovian
jovian.commit(project='numpy-array-operations')
[jovian] Updating notebook "hai-advisoryservices/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/hai-advisoryservices/numpy-array- operations 'https://jovian.ai/hai-advisoryservices/numpy-array-operations'
Let's begin by importing Numpy and listing out the functions covered in this notebook.
import numpy as np
function1 = np.multiply function2 = np.matmul function3 = np.arange function4 = np.concatenate function5 = np.stack
numpy.multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.
Syntax : numpy.multiply(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘multiply’)
arr1 = [[1, 2], [3, 4]]
arr2 = [[5, 6], [8, 9]]
np.multiply(arr1, arr2)
array([[ 5, 12], [24, 36]])
arr1 & arr2 are of similar datatypes and shape. when we use np.multiply function to these both arr1 & & arr2, numpy will automatically multiply both the matrix element by element and give us the result. rst element of rst matrix inside arr1 will get multiplied by rst element of second matrix and second element of rst matrix will get multiplied by second element of second matrix and we get the result as shown above.
arr1 = [[1, 2, 3], [3, 4, 5]]
arr2 = [[5, 6, 10], [8, 9, 12]]
np.multiply(arr1,arr2)
array([[ 5, 12, 30], [24, 36, 60]])
here we show an example of two matirces having a different shape than th e rdt example, here arr1&arr2 have the shape(2,2,3), this function helps us use this function on this shape as well, and does the same application of multiplying the two matrices element by element and give us the result as shown above.
arr1 = [[1, 2], [3, 4.]]
arr2 = [[5, 6, 7], [8, 9, 10]]
np.multiply(arr1, arr2)
ValueError Traceback (most recent call last) /tmp/ipykernel_39/2726185824.py in
function for above data and returns a product of matrix value for each row and it will perform the same operation as the rows increases.
weatherdata = [[73,67,43],[91,88,64],[87,134,58],[102,43,37],[69,96,70],[45,67,98]] weights = [0.3,0.2,0.5,0.7] np.matmul(weatherdata,weights)
ValueError Traceback (most recent call last) /tmp/ipykernel_39/245647068.py in
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 4 is different from 3)
here when we try to change the order of the values assigned to weights it gives an error because the order has been changed and it does not recall the same size which was assigned before in this case it will throw an error as shown above.
To x it we need to rectify the order by using broadcast to match the shape.
very useful function which numpy allows us to use, as it gets the computing of large number of values in very less time and also the makes it easy to get the product of the matrices as required.
jovian.commit()
[jovian] Updating notebook "hai-advisoryservices/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/hai-advisoryservices/numpy-array- operations 'https://jovian.ai/hai-advisoryservices/numpy-array-operations'
Function 3 - np.arange
Np.arange is very useful function where we can give a starting point an ending point with a step for the range.
The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop)
np.arange(10,120,5)
array([ 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115])
here we make use of np.arange as shown above, here it takes (10,120,5) so the rst value in the argument determines the starting point of an array and the second value determines the ending point of an array, the last value determines the step with which it should skip the range.
np.arange(1000,7999,453)
array([1000, 1453, 1906, 2359, 2812, 3265, 3718, 4171, 4624, 5077, 5530, 5983, 6436, 6889, 7342, 7795])
here we make use of the np.arange function. we have a higher starting point and ending point. with higher step value it still performs the operation in very less time and gives u s the result.
np.arange(100,200,3,5)
TypeError Traceback (most recent call last) /tmp/ipykernel_39/367506528.py in
TypeError: Cannot interpret '5' as a data type
here when we use the function np.arange and give 4 arguments instead of 3 which determines the starting point , ending point and the step to perform the function, it will not identify the 4th argument and throw an error as shown above. to x this we need to give standard argument which is required for np.arange function.
The advantage of numpy.arange() over the normal in-built range() function is that it allows us to generate sequences of numbers that are not integers.
jovian.commit()
[jovian] Updating notebook "hai-advisoryservices/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/hai-advisoryservices/numpy-array- operations 'https://jovian.ai/hai-advisoryservices/numpy-array-operations'
Function 4 - np.concatenate
Concatenate. Concatenation refers to joining. This function is used to join two or more arrays of the same shape along an existing axis.
Syntax : numpy.concatenate((arr1, arr2, …), axis=0, out=None)
arr1 = [[4, 2], [3, 4.]]
the above example determines when np.concatenate doesn't work. here we see that when the concatenate function is used to adding to the outermost list it will not work, as the size of the elements in arrays doesn't match. That is why we use axis=1 which adds it to the inner list and that is how we can x this issue.
the arrays should have the same number of dimensions,and the same length along each except the dimension used for concatenation. it is useful function to join two arrays to the inner list creating a new column.
jovian.commit()
[jovian] Updating notebook "hai-advisoryservices/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/hai-advisoryservices/numpy-array- operations 'https://jovian.ai/hai-advisoryservices/numpy-array-operations'
Function 5 - np.stack
stack() is used for joining multiple NumPy arrays. Unlike, concatenate(), it joins arrays along a new axis. It returns a NumPy array. to join 2 arrays, they must have the same shape and dimensions. (e.g. both (2,3)–> 2 rows, columns) stack() creates a new array which has 1 more dimension than the input arrays. If we stack 2 1-D arrays, the resultant array will have 2 dimensions.
Syntax: numpy.stack(arrays, axis=0, out=None)
a = np.array([1, 2, 3]) b = np.array([4, 5, 6])
np.stack((a, b),axis=0)
array([[1, 2, 3], [4, 5, 6]])
here we make use of the function np.stack. np.stack joins the two 1 dimensional array and create 2 dimensional array.
axis: Along this axis, in the new array, input arrays are stacked. Possible values are 0 to (n-1) positive integer for n- dimensional output array. For example, in the case of a resultant 2-D array, there are 2 possible axis options :0 and
Notice, output is a 2-D array. They are stacked row-wise.
a = np.array([1, 2, 3]) b = np.array([4, 5, 6])
np.stack((a, b),axis=1)
array([[1, 4], [2, 5], [3, 6]])
Now, here we see that the above example shows how the np.stack function is used to join two arrays and create a new arrays of 2 dimensions, column wise by using axis=1. They are stacked column wise.
a = np.array([1, 2, 3]) b = np.array([4, 5])
np.stack((a, b),axis=1)
ValueError Traceback (most recent call last) /tmp/ipykernel_39/1077407104.py in
<array_function internals> in stack(*args, **kwargs)
/opt/conda/lib/python3.9/site-packages/numpy/core/shape_base.py in stack(arrays, axis, out) 425 shapes = {arr.shape for arr in arrays} 426 if len(shapes) != 1: --> 427 raise ValueError('all input arrays must have the same shape') 428 429 result_ndim = arrays[0].ndim + 1
ValueError: all input arrays must have the same shape
Here we see that np.stack function is not giving the result, this is because the stack function joins two arrays with similar shape and dimensions it cant have different shape and dimensions.to x this we have to reshape the array in to similar shape and dimensions.
this function can be used when we need to add arrays to a new axis in contrary to the concatenate function.
jovian.commit()
[jovian] Updating notebook "hai-advisoryservices/numpy-array-operations" on https://jovian.ai [jovian] Committed successfully! https://jovian.ai/hai-advisoryservices/numpy-array- operations 'https://jovian.ai/hai-advisoryservices/numpy-array-operations'
Conclusion