How to apply Operations on Arrays using NumPy Library

How to apply Operations on ndArray using NumPy Library


NumPy Library provides lot of useful function that you can apply on n-dimensional arrays(ndarray) for scientific or mathematical computations.  In the subsequent sections we will discuss following functions provided by NumPy Library after importing it in our program.

shape( )                       
If you have an ndarray and you want to determine its dimensions then you may use shape( ) for this purpose as shown in example below;
From the above output result, i.e. ‘Out[3]: (3,3)’ after using shape( ) function, you find that you have created an array of dimension 3x3.


Arithmetic Operations (+, -, *, /)
You can use arithmetic operations i.e. addition, subtraction, multiplication and division to ndarray object. Using arithmetic operations when you use scalar value as second operand with first operand as ndarray, you will notice that you are adding/subtracting/multiplying/diving each entry of ndarray with scalar you defined as shown in following examples;

If you apply arithmetic operations between two ndarray, then you will get the resultant array obtained by addition/subtraction/multiplication/division of each element of first array to elements of corresponding locations of second array as shown below;
In this way, you can also apply other arithmetic operations between two ndarray to get the desired output.

dtype( ) & astype()
Using dtype( ) function from NumPy library you can determine the data type of elements any ndarray holds as following;

From the above example, you can find that we have created an array ‘arr2’ of data type ‘int32’. You can also get other results using function dtype( ) depending upon the data types of elements of an array that it holds.
Another function astype( ) can be used to convert an array with one data type to an array of other data type as shown below;


resize( )
If you want to convert dimension of an array to required dimensions then you may use function resize( ) as follows;
From the above you can notice that, when you convert the dimension of array to desired dimension which is very large as per total available data or elements in previous array then rest vacant positions in resultant final array will be filled with subsequent elements of previous array to be changed.


min( ) & max( )
Using functions min( ) max( ), you can find out the minimum and maximum values of number from the total numbers present in any array as mentioned in following example;


sum( ) , mean( ) & std( )
With functions sum( ) , mean( ) and std( ) from NumPy library, you can calculate sum and average respectively of total elements of an array as shown below;

argmax () & argmin( )
For calculation of indices of maximum and minimum values, you can use functions argmax( ) & argmin( ) respectively for this purpose as shown in example below;

Comments