0% found this document useful (0 votes)
35 views28 pages

43 Amol Padiyar Numpy Notes

NumPy is a Python library used for working with arrays. It allows users to work with multi-dimensional arrays and matrices for tasks like linear algebra, trigonometry, statistics, and more. NumPy arrays are fast and homogeneous data structures that can be indexed, sliced, reshaped, and mathematically operated on. Common NumPy functions include np.zeros(), np.ones(), np.random.rand(), and np.dot() for linear algebra operations.

Uploaded by

uikeaditya612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views28 pages

43 Amol Padiyar Numpy Notes

NumPy is a Python library used for working with arrays. It allows users to work with multi-dimensional arrays and matrices for tasks like linear algebra, trigonometry, statistics, and more. NumPy arrays are fast and homogeneous data structures that can be indexed, sliced, reshaped, and mathematically operated on. Common NumPy functions include np.zeros(), np.ones(), np.random.rand(), and np.dot() for linear algebra operations.

Uploaded by

uikeaditya612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

NumPy

NumPy :
NumPy is stands for Numerical Python.

It is a library in python

It is used to works with an array.

There is need to import numpy library as --> import numpy as np

In various application we can use Numpy :

1.Linear Algebra.

2.Trigonometry.

3.Statistics.

4.Matrix Operation.

5.Logarithm.

6.Probability.

7.Image Processing. etc.

Array :
o It is a collection of homogeneous data type element.

o we can create array using list or tuple.

o Numpy array is ordered and index able we can perform indexing and slicing on it.

o Numpy array is faster than list because numpy is written in C and C++

and partially in python. C is faster than python so numpy array is faster than list.

o To create array we have syntax :

Variable= np.array(list/tuple)
* How to create an array :

Types of dimensions of an Array :

The dimensions of an array is considered on the number of square


bracket at start and end of an array. Number of square bracket at start or at end
is nothing but the dimension of that array.

o Zero dimension array :

In zero only single value is in array.


There is no any square bracket in array.
To check dimension of an array we have syntax : array.ndim
Numpy array in zero dimension is an scalar.
We can not access it via indexing.
To find the shape of an array we have one function array.shape
Its shape is ()
1.One Dimensional Array :

In one dimensional array there is only one square bracket is present at


start and end and it contains number of zero dimensional element.

2. Two Dimensional Array :


In two dimensional array there is two square bracket is present at start
and end and it contains number of one dimensional element and in each one
dimensional contains number of zero dimensional element. It contains row and
column it is nothing but a matrix.

3. Three Dimensional Array :


In three dimensional array there is three square bracket is present at start
and end and it contains number of two dimensional array and in each two
dimensional array contains number of one dimensional element and in each one
dimensional contains number of zero dimensional element.
How Array is of homogeneous data type element and type structure of
array :
An array is collection of homogeneous data type element because it can
store elements of same data type only. While creating an array value or element
of an array is of same data type if we take one value of another data type then
array will convert it into same data type .
The data type structure of an array is :

Int >> float >> complex >> string/object

If we take all integer value and one float value then all value will change
to float data type.

If we take all integer/float value and one complex value then all value will
change to complex data type.

If we take all integer/float/complex value and one string value then all
value will change to string/object data type.

Change element data type of an array :

We can change element data type of an array while creating an array we can
pass one parameter that is dtype = ‘data type’ .we can change int <--> float,
Int ---> sting ,float --> string , int and float ---> complex. For data type we can
pass ‘int’, ‘float’ ,‘complex’ ,‘object’.
Indexing And Slicing on Array :
We can apply indexing and slicing on array.

1.For one dimensional array :


By passing index number in square bracket we can access element of an array.

By giving start index , end index and step size we can access part of an array.In this end
value is excluded and step size is optional.

2.For Two dimensional array :


Indexing for two dimensional array.

Slicing on 2D array
For slicing on 2D there is two colon [ : , : ] 1st is for row and 2nd is for column
3.For Three dimensional array :
For indexing on 3D array we have to pass 3 index to access element of an array
1st is for 2D element ,2nd is for 1D element and 3rd is for 0D element.

For three dimensional there is three colon [ : , : , : ] 1st is for 2D element 2nd is for rows and
3rd is for columns.
Mathematical operation on each array element :

If we are going to apply some mathematical operation on list variable It will


not carry that operation on list element.

In that case the list get repeated two times in bracket.

But in case of array that operation is done on each element of an array.

Similarly we can perform various operation like addition , subtraction ,


multiplication , square , cube , square root , cube root etc

Convert to n-D array :


We can convert 1D array to 2D , 3D or 2D array to 3D ,4D while creating
an array for this we have parameter ndmin = value by using this parameter we
can only increase the dimension of an array.
We can not decrease the dimension of an array using this so it is just to
increase the dimension of an array by increasing the square bracket.
Functions of NumPy Array :

1. Convert array to list :


we can convert array to list for this we can use these two methods.

A. Using list constructor :


Using list constructor we can convert 1D array into list.

B. Using syntax :
To convert array to list we have one function that is array.tolist( ) by using this
syntax we can convert array into list.

2. Add Array :
If we want to take addition of corresponding element of two array at that time we
have one function that is np.add(arr1,arr2). By using this function we can take addition
of two corresponding element.
But the condition is that the shape of both array should be same.

Similarly we can perform np.multiply,np.subtract,np.divide etc


3. Matrix Dot Product :
Dot product (also known as vector multiplication) is a way to calculate the
product of two vectors.
e.g we have two matrix A & B

We can calculate the dot product of two matrix using numpy library. To take dot
product of matrix we have function np.dot( array1,array2 ).
2D is nothing but matrix so we can take dot product of to matrix using numpy
function but the condition is that the number of column of first matrix should be equal to
number of rows of second matrix
4. Reshape Function :
It is used to convert an array with different dimension we can increase or decrease
the dimension of an array.
But the condition is that the number of all zero d element of an original array
should matches with number of elements in reshaped array.
To convert or change the shape of array we have function

array.reshape( shape )

To convert any n-dimensional array into 1D array for this we can pass -1 in
reshape function it will return or convert that array into 1D array.

5. np.zeros( ) :
It returns an array with all value zero along with specified shape.
It is used to create target variable.

Syntax : np.zeros( shape , dtype = ‘int’)


6. np.ones( ) :
It returns an array with vlaue one along with shape.
Syntax : np.ones(shape, dtype= ‘int’ )

7. np.arange( ) :
It is similar to range but it returns 1D array with specified range.

Syntax : arr = np.arange(start,end,stepsize)

8. np.linspace( ) :
It returns 1D array with evenly space number over a specified interval.

Syntax : arr = np.linspace(start,end,num=50,retstep=False)

By default num = 50 we can put required number of values.


By default retstep = False retstep is nothing but returns step-size . The difference
between to consecutive element is same which is nothing but retstep.
If we want to get retstep then we have to give retstep = True
9. np.eye( ) :
It returns 2D array with 1 at is diagonal position and 0 at non-diagonal position.
If we pass square matrix shape then it will return identical matrix.

Syntax : var = np.eye(shape , dtype = )

10.np.identity( ) :
It returns 2D array with 1 at its diagonal and 0 at non-diagonal position .
It consider square matrix only .Either we have to pass column number of row
number.
It returns identical matrix always.

Syntax : arr = np.identity(row /col num , dtype = ‘float’)

11.Random :

It is used to generate an array with random number elements. In various


application we can use random function of numpy such as user authentication , OTP
generation and to generate random number captcha code etc.

It has four sub functions which are as follows :


1. Random.rand
2. Random.randint
3. Random.randn
4. Random.ranf
11.1 random.rand ( ) :
It returns an array with random number between 0 and 1 interval with specified
shape.
Syntax : var = np.random.rand( shape )

11.2 random.randint ( ) :
It returns an array with random number between specified range along with
defined shape.It can be used for OTP generation with random number.

Syntax : var = np.random.randint( start , end , size = num/[shape])

At start we have to give starting value of interval and at end we have to give end
value of interval. In size if we want 1D array in output the we can give only number of
required element .we can pass required shape in size parameter but we have to pass shape
either in square [ ] or round bracket ( ) .

11.3 random.ranf ( ) :
It returns an array with random float value between 0 to 1 interval along with
specified shape. It is same as like random.rand but difference is that in rand we can
directly pass the shape but in ranf we have to pass shape in square or round bracket.
11.4 random.randn ( ) :
Randn means random normalize.It returns an array with random values from
normally distributed values ranging from -2 to +2. It returns maximum value ranging
between -2 to +2.

Syntax : var = np.random.randn ( shape )

Fig.Normally Distribution Curve

12. np.sort ( ) :
It is used to sort an array in ascending order along with axis.To sort an array in
ascending order we have function np.sort ( ).we can not sort array in descending order by
using this function.

Syntax : np.sort( array , axis = 1 )

axis = 1 ------> for column.


axis = 0 ------> for row.
By default axis is 1 means it sort an array with column if we want to sort array with rows
then we have to pass axis = 0.

Sort array with column as axis = 1 Sort array with row as axis = 0
13. -np.sort (-array ) :
By using this function we can sort array in descending order. With column or row
by passing parameter axis =1 for column and axis = 0 for row.

Syntax : -np.sort( -array , axis= 1 )

sort array in descending order with column sort array in descending order with axis

14. Numpy Stats :


We can perform various statistics operation on array in python using numpy
library such as mean, median, standard deviation and variance.

14.1 Mean :
We can calculate mean of array using numpy function i.e np.mean( ). mean is
nothing but average of element.

sum of all element.


Mean= number of element

For calculate mean we have syntax : mean = np.mean( array )

If there there is any missing value in our data so to replace that missing value we
can use mean value to replace it.
14.2 Median :
It returns middle value of an array after sorting. First it will sort the array then
gives middle value which is median of that array.
If length of array is even then it sorts array and then return average of two middle
value as median. If length of array is odd then after sorting it returns middle value as
median.
To replace missing value we can use median if there is outliers in our data so at
that time we can not use mean value to replace missing value for that we can replace it by
median value.(outliers is nothing but value beyond range)

Syntax : median = np.median( array )

14.3 Standard Deviation :


Standard deviation shows the distribution of data. It represents the deviation from
mean value .
Left side deviation = mean - xi
Right side deviation = xi - mean
sigma = standard deviation
N = Number of elements
xi = each element
mu = mean
To calculate standard deviation in python using numpy we have function np.std()

Syntax : Sd = np.std( array )


14.4 Variance :
It shows distribution of data from mean value and it a square of standard deviation.
Variance = std2
N = Number of elements
xi = each element
mu = mean

To calculate variance we have function in numpy i.e. np.var( )

Syntax : variance = np.var ( array )

15. Mode :
It is not numpy function for this we have to import stats form scipy.

Syntax : from scipy import stats

Mode is the value of our data which occurrence is maximum as compared to other
values . so to calculate mode we have function stats.mode( ).
If there is categorical column in our data so to replace the missing value of that
column we can not perform mean and median so at that time we can use mode to replace
the missing value of categorical column.
Mode function returns the maximum occurrence value with its count.so to replace
the missing value we have to use 0th index of mode output.

Syntax : mode = stats.mode( array )


16. Linear Algebra :

We can solve the linear algebraic equation using numpy library also we can
calculate the inverse of matrix .for this we have function np.linalg.solve( ) and
np.linalg.inv( ) .
To solve the linear algebraic equation we have to create two arrays 1st is 2D which
can be created with values of coefficients of two equation and 2nd is 1D array which can
be created by using value at right side or after equal operator.

To solve linear algebraic equation :

Syntax : result = np.linalg.solve( array1 , array2 )

To get inverse matrix :

Syntax : inverse = np.linalg.inv ( array )

e.g. If we have two equation like :


10x+5y = 4
8x+2y = 26

If we are going to calculate the value of x and y so we have to create array of two
equation.like

array 1 =[[10,5],
[8,2]]

Array 2 = [4,26]

Creating array of equation solving value of x & y and calculate inv


17. Trigonometric :
We can perform trigonometric calculation with numpy library.such as convert
angle degree to radian ,radian to degree , we can calculate the angles like sin cos tan etc.
To access value of pi we two library from which we can get value of pi.
1. import math
Math.pi

2. import numpy as np
Np.pi

While calculating the values of sin cos tan at that time we have to pass angle in radian .
and we have function for angles is :
np.sin( ) , np.cos( ), np.tan( ). angles should be in radian.

To convert angle degree to radian we have function :


np.deg2rad( array )

To convert angle radian to degree we have function :


np.rad2deg( array )

Fig.Converting angle degree to radian

Fig. Converting angle radian to degree

Calculating sin angle similarly we can


find cos tan values using np.cos and
np.tan
18. Logarithmic Functions :
It is used in logistic regression algorithm. Whenever we need to find log we use
logarithmic function . In numpy we have function to calculate log values like loge ,
log2 ,log10 .
To calculate log values we have functions :
For natural log i.e. loge.
np.log( ) , np.log2( ) , np.log10( ).

Log Transformation :
To reduce impact of outliers we can use log transformation to handle outliers.
By log transformation we are scaling down the values.

19. Append :
Use to append value in array. In append function value is appended at last position.

Syntax : np.append(array , value/array , axis = None )

We can pass value and array in append function .by default axis = None which
returns flatten array with append value at last position .If we pass two array having same
shape then we can pass axis = 1 and 0 in which array2 is appended in array 1 with
column and row wise respectively.
20. Concatenate :
It is used to concatenate array we can concatenate multiple array by passing list of
arrays in concatenate function but the condition is the array should be of same shape.

Syntax : np.concatenate([arr_1,arr_2,arr_3,…..,arr_n],axis=0)

21. np.nditer :
It same works as like for loop but if we have multidimensional array to access
elements of that array we need to use nested for loop.but in case of np.nditer() there is no
need to use nested loop it return each element from array.
No matter whatever the dimension of array it will return single element when we
are using in for loop.

Syntax : for i in np.nditer(array) :

Need to use nested for loop using np.nditer return each element

22. np.ndenumerate( ) :
It returns each element of an array with its exact index position in that array.

Syntax : for index , element in np.ndenumerate(array):


23. np.ceil( ) :
It returns closest and greatest integer value of an float element of array.
Dtype is always in float.

Syntax : np.ceil( array )

24. np.floor( ) :
It returns closest and smallest integer value of an float element of array.
Dtype is always in float.

Syntax : np.floor ( array )

25. np.around( ) :
It works same as like built in function round .It round up the decimal value of
each element of an array.

Syntax : np.around( array , value )

Value = number of digit after decimal.


26. np.where( ) :
It will give index value of an element from array.If element have multiple
occurrence then it will give all indices of that element in list.

Syntax : np.where(array = = element)

If we pass 2D array then it gives two list one is of the index of row in which that
element is present and second is of index of element present in respective row.

27. np.argmax( ) :
It returns index of maximum value of an array.

Syntax : np.argmax( array , axis = None )

By default axis = None so if we pass an array then it will flatten the array and
then return index of maximum element if we pass 2D array then we can give axis = 1 or
axis = 0 It gives index of rows contains max value when axis = 0 and gives index of
column which contains maximum value if axis = 1.
28. np.delete( ) :
It is used to delete the element from an array which is present at particular index
that we have pass in function.

Syntax : np.delete(array , object , axis = None )

At Object place we pass the we pass the index value of element which we want to
remove. We can pass list of indexes to delete multiple element present at that indices.

By default axis is None it will flatten the array then it will delete the element
which is present at that index. If axis = 0 then it will delete the element which present at
that index may be row if we pass 2D array.or 2D element if we pass 3D array. If axis = 1
then it will delete the column which present at particular index if we pass 2D array.

29. np.max( ) :
It returns maximum value from an array.

Syntax : np.max(array , axis = None )

If axis = None then it flatten the array then it will return the maximum value from
array. If axis = 0 then it will return the maximum element from each row. If axis = 1 then
it will return maximum element from each column .
30. np.min( ) :
It returns minimum value from an array.

Syntax : np.min(array , axis = None )

If axis = None then it flatten the array then it will return the minimum value from
array. If axis = 0 then it will return the minimum element from each row. If axis = 1 then
it will return minimum element from each column .

31. np.minimum( ) :
It returns minimum value from two arrays by comparing with corresponding
element .but the condition is that both array should be of same shape.

Syntax : np.minimum(array1,array2)

32. np.maximum( ) :
It returns maximum value from two arrays by comparing with corresponding
element .but the condition is that both array should be of same shape.
Syntax : np.maximum(array1,array2)
33. np.square( ) :
It returns square of each element of an array.

Syntax : np.square(array)

34. np.sqrt( ) :
It returns square root of each element of an array.

Syntax : np.sqrt(array)

35. np.cbrt( ) :
It returns cube root of each element of an array.

Syntax : np.cbrt(array)
36. np.power( ) :
It return the power index value of each element of an array.

Syntax : np.power(array , value)

37. flatten( ) :
It is used to convert n - dimensional array into one dimensional array.

Syntax : array.flatten( )

38. Ravel( ) :
It return 1D array with reference to the original array if we made any changes in
ravel variable array then it will also reflect in original data.

Syntax : array.ravel( )
39. copy( ) :
It is same as copy function used for list but here it is suitable of every dimensional
array so it is also called as deepcopy of numpy.we can create one array and that array is
assigned to another variable if we make changes in any of array it will reflected in
another array also so for this we can use copy function. It make make copy of an array
but if we made any changes in one of array it will not reflected to another array.

Syntax : array2 = array1.copy( )

Without copy function with copy function

40. np.full( ) :
It returns an array with same value /element along with specified shape.

Syntax : var = np.full([shape],value)

You might also like