VUnit Python
VUnit Python
The Python Standard Library is a collection of exact syntax, token, and semantics of
Python.
Python has a huge collection of libraries.
The Python Standard Library contains hundreds of modules for performing common
tasks,
Python’s standard library is very extensive, offering a wide range of facilities.
A Python library is a reusable chunk of code that you may want to include in your
programs/ projects.
Mostly it is written in C, and handles functionality like I/O and other core modules.
Python supports very huge number of library files. Some examples are:
Numpy
SciPy
Pandas
Matplotlib
Scikit-Learn
Seaborn
Keras
PyTorch
TensorFlow
1
A library is a collection of modules.
Module Definition: The module is a simple Python file that contains collections of
functions and global variables and with having a .py extension file.
Package Definition: The package is a simple directory having collections of modules.
This directory contains Python modules and also having __init__.py file by which the
interpreter interprets it as a Package.
Module can contain multiple objects, such as classes, functions, etc.
A package can contain one or more relevant modules.
A package is actually a folder containing one or more module files.
The package folder contains a special file called __init__.py, which stores the package's
content.
import statement:
A file is considered as a module in python. To use the module, you have to
import it using the import keyword.
import modules from packages using the dot (.) operator.
import [Link]
Syntax: Example:
2
from module_name import member_name from math import pi
Syntax: Example:
Example: Output:
3
def add(a,b):
c=a+b
print(f"Addition is :{c} ")
[Link]
def add(a,b):
c=a+b
print(f"Addition is :{c} ")
[Link]
import [Link]
import [Link]
[Link](10,20)
[Link](50,30)
5.4 Numpy
4
NumPy is the fundamental package for scientific computing with Python, adding support
for large, multidimensional arrays and matrices, along with a large library of high-level
mathematical functions to operate on these arrays.
Features OfNumpy
Interactive: Numpy is very interactive and easy to use.
Mathematics: Makes complex mathematical implementations very simple.
Intuitive: Makes coding real easy and grasping the concepts is easy.
Lot of Interaction: Widely used, hence a lot of open source contribution
Applications Of Numpy
Extensively used in data analysis
Creates powerful N-dimensional array
Forms the base of other libraries, such as SciPy and scikit-learn
Replacement of MATLAB when used with SciPy and matplotlib
Example: Output:
import numpy as np [1 2 3 4 5]
a=[Link]([1,2,3,4,5]) [[1 2 3]
b=[Link]([[1,2,3],[4,5,6]]) [4 5 6]]
print(a) <class '[Link]'>
print(b) 2
print(type(a)) 3
print([Link]) [2 3]
print(a[2]) [0 2 3 4 5]
print(a[1:3]) (2, 3)
x = [Link]()
x[0]=0
print(x)
print([Link])
5
5.5 SciPy
Features of Scipy
Collection of algorithms and functions built on the NumPy extension of Python
High-level commands for data manipulation and visualization
Multidimensional image processing with the SciPy ndimage submodule
Includes built-in functions for solving differential equations
Applications of Scipy
Multidimensional image operations
Solving differential equations and the Fourier transform
Optimization algorithms
Linear algebra
Subpackages in SciPy
6
[Link] Image manipulation
Example: Output:
c = [Link](90)
print(c)
d = [Link](45)
print(d)
d = [Link](45)
print(d)
5.6 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.
It is used to create a wide variety of visualizations, including line plots, histograms, bar
charts, pie charts, scatter plots, tables, and many other styles.
Matplotlib is a Python 2D plotting library that produces publication-quality figures in a
variety of hard-copy formats and interactive cross-platform environments.
This 2D plotting library of Python is very famous among data scientists for designing
varieties of figures in multiple formats which is compatible across their respected
platforms.
Features of Matplotlib:
Usable as a MATLAB replacement, with the advantage of being free and open
source
Supports dozens of backends and output types, which means you can use it
regardless of which operating system you’re using or which output format you
wish to use
7
Pandas itself can be used as wrappers around MATLAB API to drive MATLAB
like a cleaner
Low memory consumption and better runtime behavior
Applications of Matplotlib:
Correlation analysis of variables
Visualize 95 percent confidence intervals of the models
Outlier detection using a scatter plot etc.
Visualize the distribution of data to gain instant insights
Example: Output:
x = [Link]([0, 6])
y = [Link]([0, 250])
[Link](x, y)
[Link]()
x = [Link]([1, 2, 6, 8])
y = [Link]([3, 8, 1, 10])
[Link](x, y,'*r--')
[Link]("Example")
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]()
[Link]()
8
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias.
plot() function draws a line from point to point.
keyword argument marker to emphasize each point with a specified marker
title() function to set a title for the plot.
xlabel() and ylabel() functions to set a label for the x- and y-axis
grid() function to add grid lines to the plot.
bar() function to draw bar graphs
pie() function to draw pie charts
5.7 Pandas
9
Easy reshaping and pivoting of data sets
Merging and joining of data sets
Label-based data slicing, indexing, and subsetting
working with time-series data
Eloquent syntax and rich functionalities that gives you the freedom to deal with
missing data
Enables you to create your own function and run it across a series of data
High-level abstraction
Contains high-level data structures and manipulation tools
Manipulating data will be easier.
Support for various operations such as Re-indexing, Iteration, Sorting,
Aggregations, Concatenations and Visualizations.
Applications Of Pandas
It is the best data analysis tool available for solving real-world problems
General data wrangling and cleaning
It is the best data analysis tool available for solving real-world problems
ETL (extract, transform, load) jobs for data transformation and data storage, as it
has excellent support for loading CSV files into its data frame format
Used in a variety of academic and commercial areas, including statistics, finance
and neuroscience
Time-series-specific functionality, such as such as date range generation, moving
window, linear regression and date shifting.
Example: Output:
import pandas as pd States Capitals
df = [Link]({'States':['TN', 'AP', 'UP', 'MP'], 0 TN CHENNAI
'Capitals':['CHENNAI', 'AMARAVATHI', 1 AP AMARAVATHI
'LUCKNOW', 'BHOPAL']}) 2 UP LUCKNOW
df.to_excel('[Link]') 3 MP BHOPAL
df = pd.read_excel('[Link]')
print(df)
10
import pandas library alias name is pd.
Data sets in Pandas are usually multi-dimensional tables, called DataFrames.
loc attribute to return one or more specified row(s)
dropna() - remove rows that contain empty cells.
fillna() - replace empty cells with a value
mean() - to calculate the mean value of the column
median() - to calculate the median value of the column
mode() - to calculate the mode value of the column
drop_duplicates() – remove duplicates rows
5.8 scikit-Learn
11
Simple and efficient tools for predictive data analysis.
It helps in all aspects and algorithms of Machine Learning, even Deep
Learning.
It is easy to learn and use.
Applications of Scikit-Learn
clustering
classification
regression
model selection
dimensionality reduction
Modelling process in Scikit-Learn
Dataset Loading - A collection of data is called dataset.
Preprocessing the Data - Before inputting that data to machine learning
algorithms, we need to convert it into meaningful data. This process is called
preprocessing the data.
Splitting the dataset - To check the accuracy of our model, we can split the
dataset into two pieces-a training set and a testing set.
Train the Model- use our dataset to train some prediction-model.
Example: Output:
import pandas as pd (1067, 13)
import [Link] as plt [126.18920155]
from sklearn.model_selection import Actual Predicted
train_test_split 0 356 342.055315
from sklearn.linear_model import 1 209 220.385324
LinearRegression 2 230 220.385324
3 212 232.159839
dataset=pd.read_csv("[Link]") 4 168 224.310162
print([Link]())
print([Link])
X = dataset['ENGINESIZE'].[Link](-1,1)
y = dataset['CO2EMISSIONS'].[Link](-
1,1)
X_train, X_test, y_train, y_test =
train_test_split(X, y, test_size=0.2,
random_state=0)
regr = LinearRegression()
[Link](X_train, y_train)
print(regr.intercept_)
y_pred = [Link](X_test)
12
df = [Link]({'Actual': y_test.flatten(),
'Predicted': y_pred.flatten()})
print(df)
[Link]()
5.9 seaborn
Example: Output:
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
dataset=pd.read_csv("[Link]")
[Link](dataset['CO2EMISSIONS'],hist=False)
[Link](x = "ENGINESIZE",y =
'CO2EMISSIONS',data = dataset,kind='hex')
[Link]("CO2EMISSIONS", data=dataset,
color='green',kind='count')
14