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

Unit 5 Notes Python

The document provides an overview of Python packages, explaining their purpose in organizing code into reusable components, and details on how to create a package. It also covers Numpy, a powerful library for array processing, including array creation, indexing, basic operations, and data types. Additionally, it introduces Matplotlib, a library for creating visualizations, highlighting its features, workflow, and applications.

Uploaded by

mrayush2020
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)
3 views

Unit 5 Notes Python

The document provides an overview of Python packages, explaining their purpose in organizing code into reusable components, and details on how to create a package. It also covers Numpy, a powerful library for array processing, including array creation, indexing, basic operations, and data types. Additionally, it introduces Matplotlib, a library for creating visualizations, highlighting its features, workflow, and applications.

Uploaded by

mrayush2020
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/ 13

Packages in python

We usually organize our files in different folders and subfolders based on some criteria, so that they can be managed
easily and efficiently. For example, we keep all our games in a Games folder and we can even subcategorize according to
the genre of the game or something like that. The same analogy is followed by the Python Packages

What is a Python Package?


Python Packages are a way to organize and structure your Python code into reusable components. Think of it like a folder
that contains related Python files (modules) that work together to provide certain functionality. Packages help keep your
code organized, make it easier to manage and maintain, and allow you to share your code with others. They’re like a
toolbox where you can store and organize your tools (functions and classes) for easy access and reuse in different projects.
How to Create Package in Python?
Creating packages in Python allows you to organize your code into reusable and manageable modules. Here’s a brief
overview of how to create packages:
• Create a Directory: Start by creating a directory (folder) for your package. This directory will serve as the
root of your package structure.
• Add Modules: Within the package directory, you can add Python files (modules) containing your code. Each
module should represent a distinct functionality or component of your package.
• Init File: Include an __init__.py file in the package directory. This file can be empty or can contain an
initialization code for your package. It signals to Python that the directory should be treated as a package.
• Subpackages: You can create sub-packages within your package by adding additional directories containing
modules, along with their own __init__.py files.
• Importing: To use modules from your package, import them into your Python scripts using dot notation. For
example, if you have a module named module1.py inside a package named mypackage, you would import
its function like this: from mypackage.module1 import greet.
• Distribution: If you want to distribute your package for others to use, you can create a setup.py file using
Python’s setuptools library. This file defines metadata about your package and specifies how it should be
installed.
Code Example
Here’s a basic code sample demonstrating how to create a simple Python package:
1. Create a directory named mypackage.
2. Inside mypackage, create two Python files: module1.py and module2.py.
3. Create an __init__.py file inside mypackage (it can be empty).
4. Add some code to the modules.
5. Finally, demonstrate how to import and use the modules from the package.
mypackage/

├── __init__.py
├── module1.py
└── module2.py
Example: Now, let’s create a Python script outside the mypackage directory to import and use these modules:
1
# module1.py
2
def greet(name):
3
print(f"Hello, {name}!")

When you run the script, you should see the following output:
Hello, Alice!
The result of addition is: 8

Python Numpy

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for
working with these arrays. It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.
Arrays in Numpy
Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy,
number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is
known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square
brackets and can be initialized by using nested Python Lists.
Creating a Numpy Array
Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be
created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the
elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.
# Python program for
# Creation of Arrays
import numpy as np

# Creating a rank 1 Array


arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)

# Creating a rank 2 Array


arr = np.array([[1, 2, 3],
[4, 5, 6]])
print("Array with Rank 2: \n", arr)

# Creating an array from tuple


arr = np.array((1, 3, 2))
print("\nArray created using "
"passed tuple:\n", arr)

1
# Python program for
2
# Creation of Arrays
3
import numpy as np
4

5
# Creating a rank 1 Array
6
arr = np.array([1, 2, 3])
7
print("Array with Rank 1: \n",arr)
8

9
# Creating a rank 2 Array
10
arr = np.array([[1, 2, 3],
11
[4, 5, 6]])
12
print("Array with Rank 2: \n", arr)
13

14
# Creating an array from tuple
15
arr = np.array((1, 3, 2))
16
print("\nArray created using "
17
"passed tuple:\n", arr)

Output
Array with Rank 1:

[1 2 3]

Array with Rank 2:

[[1 2 3]

[4 5 6]]

Array created using passed tuple:

[1 3 2]

Accessing the array Index


In a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is
done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original
array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array
modifies the original array content.
# Python program to demonstrate
# indexing in numpy array
import numpy as np

# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)

# Printing a range of Array


# with the use of slicing method
sliced_arr = arr[:2, ::2]
print ("Array with first 2 rows and"
" alternate columns(0 and 2):\n", sliced_arr)

# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
"(1, 2), (0, 1), (3, 0):\n", Index_arr)

# Python program to demonstrate


# indexing in numpy array
import numpy as np

# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)

# Printing a range of Array


# with the use of slicing method
sliced_arr = arr[:2, ::2]
print ("Array with first 2 rows and"
" alternate columns(0 and 2):\n", sliced_arr)

# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
"(1, 2), (0, 1), (3, 0):\n", Index_arr)

Basic Array Operations


In numpy, arrays allow a wide range of operations which can be performed on a particular array or a combination of
Arrays. These operation include some basic Mathematical operation as well as Unary and Binary operations.

# Python program to demonstrate


# basic operations on single array
import numpy as np

# Defining Array 1
a = np.array([[1, 2],
[3, 4]])

# Defining Array 2
b = np.array([[4, 3],
[2, 1]])

# Adding 1 to every element


print ("Adding 1 to every element:", a + 1)

# Subtracting 2 from each element


print ("\nSubtracting 2 from each element:", b - 2)

# sum of array elements


# Performing Unary operations
print ("\nSum of all array "
"elements: ", a.sum())

# Adding two arrays


# Performing Binary operations
print ("\nArray sum:\n", a + b)

Output
Adding 1 to every element: [[2 3]

[4 5]]

Subtracting 2 from each element: [[ 2 1]

[ 0 -1]]

Sum of all array elements: 10

Array sum:

[[5 5]

[5 5]]

Data Types in Numpy


Every Numpy array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
Every ndarray has an associated data type (dtype) object. This data type object (dtype) provides information about the
layout of the array. The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of
memory bytes which can be interpreted by the dtype object. Numpy provides a large set of numeric datatypes that can be
used to construct arrays. At the time of Array creation, Numpy tries to guess a datatype, but functions that construct
arrays usually also include an optional argument to explicitly specify the datatype.
Constructing a Datatype Object
In Numpy, datatypes of Arrays need not to be defined unless a specific datatype is required. Numpy tries to guess the
datatype for Arrays which are not predefined in the constructor function.
# Python Program to create

# a data type object


import numpy as np

# Integer datatype

# guessed by Numpy

x = np.array([1, 2])

print("Integer Datatype: ")

print(x.dtype)

# Float datatype

# guessed by Numpy

x = np.array([1.0, 2.0])

print("\nFloat Datatype: ")

print(x.dtype)

# Forced Datatype

x = np.array([1, 2], dtype = np.int64)

print("\nForcing a Datatype: ")

print(x.dtype)

Output
Integer Datatype:

int64

Float Datatype:

float64

Forcing a Datatype:

int64

Math Operations on DataType array


In Numpy arrays, basic mathematical operations are performed element-wise on the array. These operations are applied
both as operator overloads and as functions. Many useful functions are provided in Numpy for performing computations on
Arrays such as sum: for addition of Array elements, T: for Transpose of elements, etc.

# Python Program to create

# a data type object

import numpy as np

# First Array
arr1 = np.array([[4, 7], [2, 6]],

dtype = np.float64)

# Second Array

arr2 = np.array([[3, 6], [2, 8]],

dtype = np.float64)

# Addition of two Arrays

Sum = np.add(arr1, arr2)

print("Addition of Two Arrays: ")

print(Sum)

# Addition of all Array elements

# using predefined sum method

Sum1 = np.sum(arr1)

print("\nAddition of Array elements: ")

print(Sum1)

# Square root of Array

Sqrt = np.sqrt(arr1)

print("\nSquare root of Array1 elements: ")

print(Sqrt )

# Transpose of Array

# using In-built function 'T'

Trans_arr = arr1.T

print("\nTranspose of Array: ")

print(Trans_arr)

Output
Addition of Two Arrays:

[[ 7. 13.]

[ 4. 14.]]

Addition of Array elements:

19.0
Square root of Array1 elements:

[[2. 2.64575131]

[1.41421356 2.44948974]]

Transpose of Array:

[[4. 2.]

Matplotlib

Matplotlib is a comprehensive library in Python used for creating static, animated, and interactive visualizations. It is highly flexible,
allowing users to produce a wide variety of plots, from simple line plots to complex 3D visualizations. Matplotlib se rves as the
foundation for other visualization libraries like Seaborn and Pandas’ plotting functions.

Key Features

1. Wide Variety of Plots:

• Line plots, scatter plots, bar charts, histograms, pie charts, error bars.

• Advanced plots like 3D plots, polar plots, quiver plots, and contour plots.

2. Customizability:

• Every element of the plot (e.g., labels, ticks, colors, markers, lines) can be customized to meet specific requirements.

3. Integration:

• Compatible with NumPy for numerical computations.

• Works seamlessly with Pandas DataFrames for data visualization.

• Can be used in Jupyter Notebooks for interactive visualizations.

4. Interactive Mode:

• Allows interactive exploration of data by zooming, panning, or updating plots dynamically.

5. Output Support:

• Supports a range of output formats, including PNG, PDF, SVG, and more.

Core Components of Matplotlib

1. Figure:

• The outermost container for a Matplotlib plot.

• Contains one or more subplots or axes.

2. Axes:

• The main area where data is plotted. Each plot is an instance of the Axes class.

• Contains elements like labels, title, gridlines, and legends.

3. Artist:

• Everything in Matplotlib (lines, text, markers, etc.) is an instance of the Artist class.

4. Pyplot:

• A module in Matplotlib (matplotlib.pyplot) that provides a MATLAB-like interface for creating visualizations.

Matplotlib Workflow
1. Import the Library:

import matplotlib.pyplot as plt

2. Prepare Data:
Use lists, NumPy arrays, or Pandas DataFrames to organize your data.

3. Create a Plot:
Example of a simple line plot:

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

4. Customize:
Add titles, legends, colors, and more.

5. Save the Plot:

plt.savefig("plot.png")

Advanced Features

1. Subplots:
Allows multiple plots within a single figure.

fig, axs = plt.subplots(2, 2)


axs[0, 0].plot(x, y)
axs[0, 1].scatter(x, y)
axs[1, 0].bar(x, y)
axs[1, 1].hist(y)
plt.tight_layout()
plt.show()

2. Styling:

• Use plt.style.use('style_name') for predefined styles like ggplot, seaborn, etc.

3. 3D Plotting:
Requires the mpl_toolkits.mplot3d module.

from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
plt.show()

4. Animations:
Create dynamic plots using the FuncAnimation module.

Applications

• Data Analysis: Visualize trends, correlations, and distributions.

• Scientific Research: Create publication-quality figures.

• Machine Learning: Plot learning curves, confusion matrices, and feature importance.

• Business Analytics: Visualize sales, revenue, and customer trends.

Strengths

• Extensive documentation and community support.


• Highly customizable.

• Compatible with multiple platforms and frameworks.

Limitations

• Can be verbose compared to higher-level libraries like Seaborn.

• Some complex visualizations require significant setup.

Common Alternatives

• Seaborn: Built on top of Matplotlib; offers a high-level interface.

• Plotly: Provides interactive and web-based visualizations.

• Bokeh: For interactive and scalable visualizations in web applications.

Examples-

Matplotlib is a comprehensive library for creating static, animated, and interactive


visualizations in Python. Below are some of the example plots that can be made
using the Matplotlib library.

Installation Using pip


!pip install matplotlib

Matplotlib is a very vast library, but in this module we’ll just talk about plotting the 2-D
graphs. Most of the matplotlib utilities lies under the pyplot submodule and it is usually
impoterd under the pltalias, so for 2-D plots we will use the pyplot submodule. So let’s
import the module and start plotting a very simple graph using the plot function, which takes
two iterables as the input and returns a plotted graph using the given coordinates.

# Importing pyplot submodule from matplotlib as plt


import matplotlib.pyplot as plt

Plotting
plt.plot()

plt.plot([1,2,3,4],[1,4,2,3])
plt.show()
plt.scatter()

Now if we want to plot individual points rather than connecting them using a line, we can use
another function called scatter which takes the same input format.

plt.scatter([1,2,3,4],[1,4,2,3])
plt.show()

If you’ve noticed every time we plot a graph, we call plt.show() function. This is because
everytime, we start plotting a graph, matplotlib maintains a graph buffer so that we can plot
multiple graphs in a single plane, and whenever plt.show() is called, it flushes the maintained
buffer

#Plotting 4 Graphs in one plane


plt.plot([1,2,3,4],[1,4,2,3], c="lightblue") # c parameter is for defining color
plt.plot([1,2,3,4],[4,1,3,2], c="lightgreen")
plt.scatter([1,2,3,4],[1,4,2,3], c="darkblue")
plt.scatter([1,2,3,4],[4,1,3,2], c="darkgreen")
plt.show()

We can also provide a list of colors in the c parameter, to define color of every seperate
point.

plt.scatter([5,3,4,1,2],[2,3,4,3,5], c =["red","blue","green","red","black"])
plt.show()
plt.bar() & plt.pie()

Similarly, we have some other data visualisation functions like : BarGraphs, PieCharts, etc.
So let’s try and plot each of them and we can use another function called subplot to plot
multiple graphs in a single plot.

There are tons of other parameters too in these plots, that can make the representation more
representative and useful. For eg:

plt.xlabel("X - Axis") –> Used to represent X-Axis label

plt.ylabel("Y - Axis") –> Used to represent Y-Axis label

plt.title("Graph Title") –> Used to give graphs a Title

plt.legends() –> Used to define a legend for graph.

# subplot signature => subplot(nrows, ncols, index, **kwargs)


import numpy as np
plt.figure(figsize=(15,5))

# ---Bar Graph at 1st index of subplot---


plt.subplot(1,2,1)

Products = np.array(["P1","P2","P3","P4","P5"])
Sale2020 = np.array([200,100,400,100,400])
Sale2021 = np.array([300,200,300,400,300])

plt.title("Product Sales in 2020 v/s 2021")


plt.xlabel("Product Names")
plt.ylabel("Sale Quantity")

plt.bar(Products,Sale2020, align = 'edge' ,width = 0.5, label="2020 Sales")


plt.bar(Products,Sale2021, align = 'center',width = -0.5, label="2021 Sales")
plt.legend()

# --- Pie Chart at 2nd index of subplot ---


plt.subplot(1,2,2)
plt.title("Market Share of the Investors")
Investors = ["A","B","C","D","E"]
Share = [40,25,20,10,5]
plt.pie(Share, labels = Investors,explode=[0,0,0,0,0.2], normalize=True)

plt.show()

You might also like