Technology

Programming

Post Page Advertisement [Top]

NumpyProgramming LanguagesPython

Introduction to Numpy with basic functions

Numpy Introduction

Numpy is a python library for scientific computation (simply say mathematical calculation). It mainly works with arrays (include 2D array, 3D and many more) to calculate the various type of factors. We can treat the 2D array as a matrix, actually, we really treat the 2D array as a matrix and perform various matrix operations.

First, see how to create an array in Python using Numpy

1- Import Numpy module and give any short name for it using "as" operator in python
2- Make a python list with integer or float data type
3- Pass list to NumPy array function 

Now see some basic functions that can be applied on NumPy array

Here we are supposing "arr" is our array name

1- ndim will return the dimensions of the array
Syntax -  arr.ndim

2- shape will return the number of rows and columns in the given array
Syntax - arr.shape

3 - zeros() will return an array (it can be 1D, 2D or ND depending on the parameters you passed) with all the elements value 0
Note- for more than 1 parameter you need to pass tuple otherwise you will get error

4- ones() will return an array (it can also be 1D,2D or ND depending on the parameters you passed) with all the elements value 1
Note- for more than 1 parameter you need to pass tuple otherwise you will get error

5 - eye() will return an identity matrix i.e all the diagonals elements value will be 1 and other elements value will be 0

6 - diag() will return matrix, first you need to pass a list now all the elements present in the list will become diagonal elements one by one and you will see your list elements in diagonal of the matrix
and other elements value will be 0

Now let's see some more useful functions

Here we are treating NumPy as np
1- np.random.rand(n) will give you n random numbers of values all between 0 to 1.
Note - n can be any integer here

2- np.random.randint(start,end,n) will give n random numbers all between start (inclusive integer) to end (exclusive integer).
Note - Here start, end, n can be any integer

3 - np.random.randn(n) will return all the numbers between -1 to 1 and considering 0 as a centre.
Note - here 0 can be any integer


Reshaping data in NumPy

Reshaping means converting 1D to 2D or 2D to 3D or 2D to 1D and so on.
- Suppose "arr" is our 1D array, now to convert arr to 2D the number of elements in 1D array must be the same as the number of  elements in 2D array with condition m*n = p
where p = total number of elements in 1D array
           m = number of rows
           n = number of columns

To reshape use reshape() function over arr array
==> arr.reshape()











No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib