0% found this document useful (0 votes)
52 views

Numpy

Uploaded by

Yash
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)
52 views

Numpy

Uploaded by

Yash
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/ 37

Numpy

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
function/module/package/library in Python

Function

Module

Package

Library

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
What is the Python Libraries?

● A module is a file consisting of Python code.


● A module can define functions, classes and variables.A module
can also include runnable code.
● A library is a collection of files (called modules) which contain
pre-written code that other developers have created for us
● A library is a collection of modules.

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
How to use Python Libraries?
NumPy: NumPy (Numerical Python) is a perfect tool for scientific computing and performing basic and
advanced array operations.

SciPy :This useful library includes modules for linear algebra, integration, optimization, and statistics.

Pandas: Pandas is a library created to help developers work with "labeled" and "relational" data intuitively.

Matplotlib: Matplotlib helps with data analyzing, and is a numerical plotting library.

Pillow: Pillow is a friendly fork of PIL (Python Imaging Library), but is more user-friendly.

SciKit-Learn: This is an industry-standard for data science projects based in Python.

Keras: Keras is a great library for building neural networks and modeling.
PyTorch: PyTorch is a framework that is perfect for data scientists who want to perform deep learning
tasks easily.

TensorFlow :TensorFlow is a popular Python framework for machine learning and deep learning,
which was developed at Google Brain

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
What is NumPy?

❖ NumPy stands for Numerical Python.

❖ NumPy is a Python library used for working with arrays.

❖ It also has functions for working in domain of linear algebra,


fourier transform, and matrices.

❖ NumPy was created in 2005 by Travis Oliphant. It is anopen source


projectand youcan useit freely.

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Why Use NumPy?
❖ In Python we have lists that serve the purpose of arrays, but they are
slow to process.
❖ NumPy aims to provide an array object that is up to 50x faster than
traditional Python lists.
❖ The array object in NumPy is called ndarray, it provides a lot of
supporting functions that make working with ndarray very easy.
❖ Arrays are very frequently used in data science, where speed and
resources are very important.

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
How to use Python Libraries?

Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.

Initially, wehavetoinstall it onour working


environment

we can use pip,


pip: Python’s package manager, to install and manage Python
packages.

Example: pip installnumpy

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
PyPI is the Python Package index — repository of python
modules.

pip is used to download and install packages directly from PyPI.

PyPI is hosted by Python Software Foundation.

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
How to use Python Libraries?

Import NumPy

A program must import a library module before using it.


Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Numpy :
● The most important objectdefined in NumPy is an N-dimensional
array typecalled ndarray.

● Itdescribes the collection of items of the same type.


● Every item in an ndarray takes the same size of block in the
memory.

● Example:
○ import numpy
○ arr= numpy.array( [1,4,7,8])
○ print(arr)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Numpy : Example 1

●Example: ● Output:
import numpy [1,4,7,8]
arr= numpy.array([1,4,7,8])
print(arr)

●We check its type :


● Output:
print( type(arr))
<class'numpy.ndarray'>

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Numpy : Example 2

Example: :more than onedimensions ● Output:


import numpy [[1,2]
arr1=numpy.array( [[1,2],[3,4]]) [3,4]]
print(arr1)

Example: :dtype parameter


import numpy ● Output:

a=numpy.array([2,4,6],dtype=float) [2. 4. 6.]

print(a)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Numpy : as np
NumPy as np
NumPy is usually imported under the np alias.

alias:InPythonalias are an alternatenamefor referring tothesamething.

Create an alias with the as keyword while importing:

NowtheNumPy packagecan bereferredtoas np insteadofnumpy.

import numpy asnp

arr=np.array([1, 2,3,4, 5])

print(arr)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
ndarray.shape
This array attribute returns a tuple consisting of array dimensions. Itcan also
beused toresize thearray.

Example: : ndarray.shape
● Output:
import numpy as np
(2,3)
a =np.array([[1,2,3],[4,5,6]])
ie. 2rows and 3columns
print( a.shape)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
ndarray.reshape
NumPy also provides a reshape function to resize an array.

Example: : ndarray.shape
● Output:
import numpy as np
(2,3)
a =np.array( [[1,2,3], [4,5,6]])
ie. 2rows and 3columns
print( a.shape)

(3,2)
b =a.reshape(3,2)
print( b) ie. 3rows and 2columns

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
ndimand size:
We can find the dimension of the array, whether it is a two-dimensional array
or a single dimensional array.

Example: : ndarray.ndim
● Output:
import numpy as np
2
a =np.array( [[1,2,3], [4,5,6]])
ie. Its 2dimensional array
print( a.ndim)

Example: : ndarray.size
6
print( a.size)
ie. Total no of elements in array a

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Department of Computer Engineering and Information Technology
College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - arange()
arange( ):create one dimensional array

You can find thedimension of thearray, whether it is a two-dimensional array


or a single dimensional array.

Example: : numpy.arange()
● Output:
import numpy as np
1
a =np.arange(12)
print( a.ndim) ie. Its 1dimensional array

● Output:
print(a )
[0 1234 567891011]

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - arange()
numpy.arange( [start, ]stop, [step, ]dtype=None)
Return evenly spaced values within a given interval.

Values are generated within the half-open interval [start, stop) (in other
words, the interval including start but excluding stop).

import numpy as np
g=np.arange(2) [0 1]
print(g)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - arange()
numpy.arange( [start, ]stop, [step, ]dtype=None)

Example:

import numpy as np [2 34567]


g=np.arange(2,8)
print(g)

import numpy as np [2 4 6]
g=np.arange(2,8,2)
print(g)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
max/min/sum:
we have some more operations in numpy such as to find the minimum,
maximum as well the sum of the numpy array.

Example: : numpy.min() ● Output:


import numpy as np 0
a =np.arange(8)
print( a.min())
● Output:
print( a.max())
7

print(a.sum() ) ● Output:
28

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
Additional Operations
we can perform more operations on numpy array i.e addition,
subtraction,multiplication and division of the two matrices

Example: import numpyas np ● Output:


a =np.array( [[1,2,3],[4,5,6]]) [[2 4 6]
b =np.array( [[1,2,3],[4,5,6]])
[81012]]

print( a+b) ● Output:


print(a-b ) [[000]
● Output: [00 0]]
print(a*b ) [[1 4 9]
[16 25 36]]

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
Additional Operations

all zeros
all ones

Example: import numpyas np ● Output:

b=numpy.zeros( [2,3]) [[0.0.0.]


[0.0. 0.]]

Example: import numpyas np


● Output:
b=numpy.ones( [1,2])
[[1.1.]]

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
Additional Operations
np.eye():

This function is used to develop an array which is an Identity matrix of


order n, where the matrix is square. This code gives an overview of the
‘np.eye()’ function

Example: import numpyas np


● Output:
b=numpy.eye(4, dtype=np.int64)
[[10 00]
[01 00]
[00 1 0]
[00 01]]

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
NumPy - Array Attributes
Additional Operations
np.diag():

we use ‘np.diag()’ function we can geneíate a diagonal matíix wheíe we


can specify the diagonal elements.

Example: import numpyas np


● Output:
b=numpy.diag([23,5,-5,66])
[[23 0 00]
[0 5 0 0]

[0 0 -5 0]
[0 0 0 66]]

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Random Numbers in NumPy

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
What is a Random Number?
Random number does NOT mean a different number every time. Random
means something that can not be predicted logically.

Generate Random Number


NumPy offers the random module to work with random numbers.

Example
Generate a random integer from 0 to 100: Output:
94
from numpy import random
x = random.randint(100)

print(x)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
What is a Random Number?

Generate Random Array


In NumPy we work with arrays, and you can use the two methods from the above examples to make
random arrays.

Integers
The randint() method takes a size parameter where you can specify the shape of an array.

from numpy import random


Output:
[927893130]
x=random.randint(100, size=(5))

print(x)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
What is a Random Number?

Generate Random Float


The random module's rand() method returns a random float between 0 and 1.

Example
Generate a random float from 0 to 1:

import numpy.random as np
x = np.rand() Output:
0.2341
print(x)

Department of Computer Engineering and Information Technology


College of Engineering Pune (COEP)
Forerunners in Technical Education
Exercise on Numpy
Exercise 1:

Obtaining Boolean Array from Binary Array


Convert a binary numpy array (containing only 0s and 1s) to a
boolean numpy array
a = np.array([[1, 0, 0], [1,
[[1, 0, 0],
1, 1], [0, 0, 0]])
[[ True False False]
[1, 1, 1], [ True True True]
[False False False]]
[0, 0, 0]] o = a.astype('bool’)
Input Array Desired Array

print(o)
Exercise 2:

Horizontal Stacking of Numpy Arrays


Stack 2 numpy arrays horizontally i.e., 2 arrays having the
same 1st dimension (number of rows in 2D arrays)

[[1,2,3], [[ 1 2 3 7 8 9] [ 4
[4,5,6]] 5 6 10 11 12]]
o=np.hstack((a1, a2))

[[7,8,9], print(o)
[10,11,12]] Desired Array

Input Array
Exercise :3
Generation of given count of equally spaced numbers within
a specified range
Output a sequence of equally gapped 5 numbers in the range 0
to 100 (both inclusive)

[ 0. 25. 50. 75. 100.] o= np.linspace(0, 100, 5)

print(o)
Desired Output
Exercise :4
Matrix Generation with one particular value
Output a matrix (numpy array) of dimension 2-by-3 with each
and every value equal to 5

o= np.full((2, 3), 5)
print(o)
[[5 5 5]
[5 5 5]]
o= np.ones((2,3))
Desired Output 0=a*5
print(o)
5. How to get the common items between two
python numpy arrays?

Input:
A= np.array([1,2,3,4,5,6,7])

B=np.array([2,5,7,8,9])

Desired Output:
print(np.intersect1d(A,B))
[2,5,7]
6. How to remove from one array those
items that exist in another?

Input:
a =
np.array([1,2,3,4,
5])
b =
Dnpes.iraerdrOauyt(pu[t5:,6,7,8#, From 'a' remove
all of 'b'
a9r]r)ay([1,2,3,4])
np.setdiff1d(a,b)
#> array([1, 2, 3,
4])
Department of Computer Engineering and Information Technology
College of Engineering Pune (COEP)
Forerunners in Technical Education

You might also like