Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views29 pages

Python Sem v Portion 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 29

Python Libraries

□NumPy
□MatplotLi
b
□Pandas
What is NumPy?
□ 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 stands for Numerical Python
□ It is a very useful library to perform mathematical and statistical operations in
Python
□ NumPy is an open source library available in Python, which helps in
mathematical, scientific, engineering, and data science programming.
□ NumPy is a programming language that deals with multi-dimensional arrays and
matrices.
□ On top of the arrays and matrices, NumPy supports a large number of
mathematical operations.
Why we 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.
NumPy - Ndarray Object
➢ The most important object defined in NumPy is an N-dimensional array type called ndarray.
➢ It describes the collection of items of the same type.
➢ Items in the collection can be accessed using a zero-based index.
➢ Every item in an ndarray takes the same size of block in the memory.
➢ Each element in ndarray is an object of data-type object (called 2-D Arrays
dtype) An array that has 1-D arrays as its
elements is called a 2-D array.
➢ The basic ndarray is created using an array function: numpy.array
# Create an ndarray 0-D Arrays 1-D Arrays import numpy as np
import numpy as np 0-D arrays, or Scalars, are the elements in An array that has 0-D arrays as its arr = np.array([[1, 2, 3], [4, 5, 6]])
a = np.array([1,2,3]) an array. Each value in an array is a 0-D elements is called uni-dimensional or print(arr)
print a array. 1-D array.
3-D arrays
An array that has 2-D arrays (matrices) as its elements is
Create a 0-D array with value 42 Create a 1D array
# more than one dimensions import numpy as np called 3-D array.
import numpy as np
import numpy as np arr = np.array(42) These are often used to represent a 3rd order tensor.
arr = np.array([1, 2, 3, 4, 5])
a = np.array([[1, 2], [3, print(arr)
print(arr)
4]]) print a import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
NumPy - Array Attributes
➢ ndarray.shape
This array attribute returns a tuple consisting of array
ndarray.ndim
dimensions. It can also be used to resize the array. This array attribute returns the number of array
import numpy as np dimensions.

a = np.array([[1,2,3],[4,5,6]]) # an array of evenly spaced numbers

print a.shape import numpy as np


a = np.arange(24)
# This resizes the ndarray
import numpy as np print a

a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print a
Data Types in NumPy 2024
NumPy supports a much greater variety of numerical types than Python does.
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode
string
V - fixed
chunk of
memory for
other type
( void )
Functions in NumPy
np.zeros((3,4)) — Create a 2D array of zeros of shape 3×4
d = np.arange(5, 20, 4 — Create an array of evenly spaced values (step value)
np.linspace(0,2,9) — Create an array of evenly spaced values (number of samples)
np.full((2,2),7) — Create a constant array of sevens of shape 2 × 2
np.eye(2) — Create a 2×2 identity matrix
np.random.random((2,2)) — Create an array with random values of shape 2×2.
np.empty((2,4)) — creates an empty array of shape 2×4.
Arrange()
Arrange() in NumPy Example:
numpy.arange() is an inbuilt numpy function that import numpy np
returns an ndarray object containing evenly np.arange(1, 11)
spaced values within a defined interval. For
Output
instance, you want to create values from 1 to 10;
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
you can use numpy.arange() function.
If you want to change the step, you can add a third number
Syntax: in the parenthesis. It will change the step.
numpy.arange(start, stop,step)
import numpy np
np.arange(1, 14, 4)
Start: Start of interval
Stop: End of Output:
interval array([ 1, 5, 9, 13])
Step: Spacing
between values.
Default step is 1
Reshape Data Flatten Data
Reshaping means changing the shape of
array.
an
The shape of an array is the number of elements
in each dimension. Flatten Data
By reshaping we can add or remove dimensions When you deal with some neural network like
or change number of elements in each dimension. convnet, you need to flatten the array. You can use
Syntax: flatten().
The syntax is
◦ numpy.reshape(a, newShape, order='C’) numpy.flatten(order='C')
Here, Here,
◦ a: Array that you want to reshape
◦ newShape: The new desires shape Order: Default is C which is an essential row
◦ Order: Default is C which is an essential style.
row style. Example of Flatten
import numpy as np import numpy as np
e = np.array([(1,2,3), (4,5,6)]) e=
print(e) np.array([(1,2,3),
e.reshape(3,2)
(4,5,6)])
e.flatten()
Output:
Example:
numpy.zeros() import numpy as np
np.zeros((2,2))
Output:
numpy.zeros() or np.zeros Python function is used to create a
matrix full of zeroes.
array([[0., 0.],
Syntax: [0., 0.]])

numpy.zeros(shape, dtype=float, order='C’)


Example of numpy zero with
Python numpy.zeros() Parameters
Datatype
Here,
Shape: is the shape of the numpy import numpy as np
zero array np.zeros((2,2), dtype=np.int16)
Dtype: is the datatype in numpy zeros. It is optional.
The default value is float64 Output:
array([[0, 0],
Order: Default is C which is an essential row style for [0, 0]],
numpy.zeros() in Python. dtype=
int16)
numpy.ones()
np.ones() function is used to create a matrix full of ones. Example:
numpy.ones() in Python

numpy.ones(shape, dtype=float, order='C') import numpy as np


Python numpy.ones() Parameters np.ones((1,2,3), dtype=np.int16)

Here, output:
Output:
array([[[1, 1, 1],
Shape: is the shape of the np.ones Python
array [1, 1, 1]]],
dtype=int1
Dtype: is the datatype in numpy ones. It is optional. The 6)
default value is float64
Order: Default is C which is an essential row style.
Asarray function
The asarray()function is used when you want to Example:
convert an input to an array. The input could be a
lists, tuple, ndarray, etc. # convert list to ndarray
import numpy as np
Asarray Syntax:
x = [1,2,3]
a = np.asarray(x)
numpy.asarray(data, dtype=None, print(a)
order=None)[source]
Here, # ndarray from tuple
import numpy as np
data: Data that you want to convert to an array
dtype: This is an optional argument. If not specified, x = (1,2,3)
the data type is inferred from the input data a = np.asarray(x)
print a
Order: Default is C which is an essential row style.
Other option is F (Fortan-style)
Matrix Multiplication
The Numpy matmul() function is used to return the Example:
matrix product of 2 arrays. h = [[1,2],[3,4]]
i = [[5,6],[7,8]]
Syntax: # 1*5+2*7 = 19
numpy.matmul(x, y, out=None) np.matmul(h, i)
Output:
Here,
array([[19, 22],
x,y: Input arrays. scalars not allowed
out: This is optional parameter. Usually output [43,
is stored in ndarray 50]])
NumPy Statistical Functions Example:
import numpy as np
normal_array = np.random.normal(5, 0.5,
NumPy has quite a few useful statistical functions 10)
print(normal_array)
for finding minimum, maximum, percentile
standard deviation and variance, etc from the ### Min
given elements in the array. print(np.min(normal_array))
Function Numpy ### Max
Min np.min() print(np.max(normal_array))

Max np.max() ### Mean


Mean print(np.mean(normal_array))
np.mean()
Median np.median() ### Median
print(np.median(normal_array))
Standard deviation np.std()
### Sd
print(np.std(normal_array))
Random Function
Random f u n c t io n i s used f o r generating random numbers.
from numpy import random
x = random.randint(100)
print(x)

from numpy import


random x =
random.randint(5,2)
print(x)
numpy.dot() in Python
□Numpy.dot product is a powerful library for #Linear algebra
matrix computation. For instance, you can #Dot product: product of two
compute the dot product with np.dot. arrays f = np.array([1,2])
□Numpy.dot product is the dot product of a and b. g=
numpy.dot() in Python handles the 2D arrays and perform
matrix multiplications. np.array([4,5])
### 1*4+2*5
Syntax np.dot(f, g)
numpy.dot(x, y, out=None) Output
Parameters 14

Here,

x,y: Input arrays. x and y both should be 1-D or 2-D for the
np.dot() function to work
out: This is the output argument for 1-D array scalar to be
returned. Otherwise ndarray should be returned.
Matplotlib
Matplotlib
□Matplotlib is one of the most popular Python packages used for data visualization.
□ It is a cross-platform library for making 2D plots from data in arrays.
□Installation of Matplotlib
C:\Users\Your Name>pip i n s t a l l m a t p l o t l i b
□Import Matplotlib
□Once M a t p l o t l i b is installed, import i t in your
a p p l i c a t i o n s by adding the import module statement:
□import m a t p l o t l i b
pyplot
□Matplotlib.pyplot is a collection of command style functions that make Matplotlib work like
MATLAB. Each Pyplot function makes some change to a figure.
Line plot Bar plot :
from matplotlib import pyplot as plt # importing matplotlib module
from matplotlib import pyplot as
# x-axis values
x = [5, 2, 9, 4, plt
7]
# x-axis values
# Y-axis values x = [5, 2, 9, 4,
y = [10, 5, 8, 4, 7]
2]
# Y-axis values
# Function to plot y = [10, 5, 8, 4,
plt.plot(x,y) 2]

# function to show the plot # Function to plot the bar


plt.show()
plt.bar(x,y)
# function to show the plot
plt.show()
Histogram
Plot Scatter Plot
Histogram : Scatter Plot :
# importing matplotlib module # importing matplotlib module
from matplotlib import pyplot as plt from matplotlib import pyplot as plt

# Y-axis values # x-axis values


y = [10, 5, 8, 4, 2] x = [5, 2, 9, 4,
# Function to plot histogram 7]
plt.hist(y)
# Y-axis values
# Function to show the plot
plt.show() y = [10, 5, 8, 4,
2]
# Function to plot scatter
plt.scatter(x, y)

# function to show the plot


plt.show()
Compare Two scatter Plots
Compare Two scatter Plots
import matplotlib.pyplot as plt
import numpy as np
#day one, the age and speed of 13
cars:
x=
np.array([5,7,8,7,2,17,2,9,4,1
1,12,9,6])
y=
np.array([99,86,87,88,111,86,
103,87,94,78,77,85,86])
plt.scatter(x, y)
#day two, the age and speed of 15
cars:
x=
np.array([2,2,8,1,15,8,12,9,7,
3,11,4,7,14,12])
Colors Matplotlib Markers
Set your own color of the markers:
Matplotlib Markers

import matplotlib.pyplot as plt The argument marker to emphasize


each point with a specified marker
import numpy as np
Mark each point with a circle:
import matplotlib.pyplot as plt
x=
np.array([5,7,8,7,2,17,2,9,4,1 import numpy as np
1,12,9,6])
ypoints = np.array([3, 8, 1, 10])
y=
np.array([99,86,87,88,111,86, plt.plot(ypoints, marker = 'o')
103,87,94,78,77,85,86])
plt.show()
plt.scatter(x, y, color =
'hotpink')
x=
np.array([2,2,8,1,15,8,12,9,7,
3,11,4,7,14,12])
y=
Create Labels for a Plot Create a Title for a Plot
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- import numpy as np
and y-axis.
import matplotlib.pyplot as plt
Add labels to the x- and y-axis:
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
import numpy as np
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
import matplotlib.pyplot as plt
plt.plot(x, y)
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
plt.title("Sports Watch Data")
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.xlabel("Average Pulse")
plt.plot(x, y)
plt.ylabel("Calorie Burnage")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage") plt.show()

plt.show()
Result:
Introduction to Pandas Library
□Pandas is an open-source Python Library providing high-performance
data manipulation and analysis tool using its powerful data structures.
□The name Pandas is derived from the word Panel Data – an
Econometrics from Multidimensional data. pandas is a Python library
with data
used sets.
for working
□It has functions for analyzing, cleaning, exploring, and manipulating
Why Use Pandas?
data.
□Pandas allows us to analyze big data and make conclusions based
on statistical theories.
□Pandas can clean messy data sets, and make them readable and
Relevant data is very important in data science.
relevant.
Installation and Data Structure of
Pandas
Installation of pandas
pip install pandas
Data Structure of Pandas
Pandas deals with the following three data structures −
▪Series
▪DataFrame
▪Panel
These data structures are built on top of Numpy array, which means they are
fast.
Series
□Series is a one-dimensional labeled Create a Series from ndarray
array capable of holding data of If data is an ndarray, then index passed
any type (integer, string, float, must be of the same length. If no index
python objects, etc.). The axis is passed, then by default index will be
labels are collectively called index. range(n) where n is array length, i.e.,
[0,1,2,3…. range(len(array))-1].

Create an Empty Series #import the pandas library and aliasing


#import the pandas library and aliasing as pd
import pandas as pd as pd
s = pd.Series() import pandas as pd
print s import numpy as
np
data =
np.array(['a','b','c','d']) s =
pd.Series(data)
print s
DataFrame
Create an Empty DataFrame Create a DataFrame from Lists Example 2
A basic DataFrame, which can be created The DataFrame can be created import pandas as pd
is an Empty Dataframe. using a single list or a list of lists. data = [['Alex',10],['Bob',12],['Clarke',13]]
df =
#import the pandas library and aliasing as Example 1 pd.DataFrame(data,columns=['Name','Age']
pd import pandas as pd ) print df
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame()
print df df = Its output is as follows −
pd.DataFrame(data)
Its output is as follows − print df Name
Empty DataFrame Its output is as follows − Age
Columns: [] 1 Alex
Index: [] 0 1 10
1 2 2 Bob 12
2 3 3 Clarke
3 4 13
4 5
How to read CSV file
import pandas as pd
df =
d f = p d .r e a d _ c s v ( ' d a t a . c s v ' ) pd.read_csv("FuelConsumption.csv")

print(df.to_string()) # take a look a t the


dataset d f. h e a d ( )
Here we use to_string() to print the
entire DataFrame.

You might also like