Unit 5 Notes Python
Unit 5 Notes 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
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
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]
[[1 2 3]
[4 5 6]]
[1 3 2]
# 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 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)
# 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 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)
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])
# Defining Array 2
b = np.array([[4, 3],
[2, 1]])
Output
Adding 1 to every element: [[2 3]
[4 5]]
[ 0 -1]]
Array sum:
[[5 5]
[5 5]]
# Integer datatype
# guessed by Numpy
x = np.array([1, 2])
print(x.dtype)
# Float datatype
# guessed by Numpy
x = np.array([1.0, 2.0])
print(x.dtype)
# Forced Datatype
print(x.dtype)
Output
Integer Datatype:
int64
Float Datatype:
float64
Forcing a Datatype:
int64
import numpy as np
# First Array
arr1 = np.array([[4, 7], [2, 6]],
dtype = np.float64)
# Second Array
dtype = np.float64)
print(Sum)
Sum1 = np.sum(arr1)
print(Sum1)
Sqrt = np.sqrt(arr1)
print(Sqrt )
# Transpose of Array
Trans_arr = arr1.T
print(Trans_arr)
Output
Addition of Two Arrays:
[[ 7. 13.]
[ 4. 14.]]
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
• 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:
4. Interactive Mode:
5. Output Support:
• Supports a range of output formats, including PNG, PDF, SVG, and more.
1. Figure:
2. Axes:
• The main area where data is plotted. Each plot is an instance of the Axes class.
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:
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.
plt.savefig("plot.png")
Advanced Features
1. Subplots:
Allows multiple plots within a single figure.
2. Styling:
3. 3D Plotting:
Requires the mpl_toolkits.mplot3d module.
4. Animations:
Create dynamic plots using the FuncAnimation module.
Applications
• Machine Learning: Plot learning curves, confusion matrices, and feature importance.
Strengths
Limitations
Common Alternatives
Examples-
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.
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
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:
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.show()