[go: up one dir, main page]

0% found this document useful (0 votes)
3 views39 pages

Unit 5

The document provides an overview of three Python packages: NumPy, Pandas, and Matplotlib, highlighting their purposes and key features. It includes example code for array manipulation with NumPy, data handling with Pandas, and various plotting techniques with Matplotlib. Additionally, it introduces Tkinter for creating GUI applications in Python.

Uploaded by

enhyphen240700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views39 pages

Unit 5

The document provides an overview of three Python packages: NumPy, Pandas, and Matplotlib, highlighting their purposes and key features. It includes example code for array manipulation with NumPy, data handling with Pandas, and various plotting techniques with Matplotlib. Additionally, it introduces Tkinter for creating GUI applications in Python.

Uploaded by

enhyphen240700
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

PYTHON PACKAGES: MATPLOTLIB, NUMPY, PANDAS

NumPy (Numerical Python)


Purpose: Efficient operations on large arrays and matrices.
 Key Features:

Fast array manipulation


Mathematical/statistical operations
Useful for scientific computing
EXAMPLE CODE:

 Example Code:

import numpy as np

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


print("Array:", arr)
print("Mean:", np.mean(arr))
print("Sum:", np.sum(arr))
print("Square Roots:", np.sqrt(arr))
ACCESS ARRAY ELEMENTS

 Array indexing is the same as accessing an array element.


 You can access an array element by referring to its index number.
 The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and
the second has index 1 etc.
 Example Code:

import numpy as np

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

print(arr[0])
ACCESS 2-D ARRAYS

 To access elements from 2-D arrays we can use comma separated integers representing
the dimension and the index of the element.
 Think of 2-D arrays like a table with rows and columns, where the dimension represents the
row and the index represents the column.
Example Code:
import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr[0, 1])


ACCESS 3-D ARRAYS

 To access elements from 3-D arrays we can use comma separated integers representing
the dimensions and the index of the element.
 Example code:
 Access the third element of the second array of the first array:
 import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])
NUMPY ARRAY SLICING

 Slicing arrays
 Slicing in python means taking elements from one given index to another given index.
 We pass slice instead of index like this: [start:end].
 We can also define the step, like this: [start:end:step].
 If we don't pass start its considered 0
 If we don't pass end its considered length of array in that dimension
 If we don't pass step its considered 1
EXAMPLE

 Slice elements from index 1 to index 5 from the following array:

import numpy as np

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

print(arr[1:5])
CHECKING THE DATA TYPE OF AN ARRAY

 The NumPy array object has a property called dtype that returns the data type of the array:
 Example code:
 Get the data type of an array object:

import numpy as np

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

print(arr.dtype)
SHAPE OF AN ARRAY

 The shape of an array is the number of elements in each dimension.

Get the Shape of an Array:-


 NumPy arrays have an attribute called shape that returns a tuple with each index having
the number of corresponding elements.
 Example code:-

import numpy as np

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

print(arr.shape)
PANDAS

 Purpose: Data manipulation and analysis tool built on top of NumPy.


 Pandas is an open-source Python library used for data manipulation, cleaning,
analysis, and visualization. It is built on top of NumPy.
 ✅ Key Features:
• Works with tabular data (CSV, Excel)
• Provides DataFrame and Series objects
• Useful for data cleaning and analysis
EXAMPLE

 Example code:-

import pandas as pd

mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}

myvar = pandas.DataFrame(mydataset)

print(myvar)
WHAT IS A SERIES?

 A Pandas Series is like a column in a table.


 It is a one-dimensional array holding data of any type.

Example code:-
import pandas as pd

a = [1, 7, 2]

myvar = pd.Series(a)

print(myvar)
READ CSV FILES

 A simple way to store big data sets is to use CSV files (comma separated files).
 CSV files contains plain text and is a well know format that can be read by everyone
including Pandas.
Example code:-
import pandas as pd

df = pd.read_csv('data.csv')

print(df)
VIEWING DATA

 df.head() # First 5 rows


 df.tail() # Last 5 rows
 df.info() # Summary
 df.describe() # Statistics
 df.columns # Column names
 df.shape # (rows, columns)
HANDLING MISSING VALUES

 df.isnull() # Detect missing


 df.dropna() # Drop missing
 df.fillna(0) # Replace with value
 df.fillna(method='ffill') # Forward fill
WHAT IS MATPLOTLIB

 Matplotlib is a plotting library for creating static, interactive, and animated


visualizations in Python.
It's used for plotting:
• Line charts
• Bar charts
• Histograms
• Pie charts
• Scatter plots
• Custom graphs
 It works well with NumPy, Pandas, and other scientific libraries.
BASIC PLOTTING WITH PYPLOT

 Example code:-

import matplotlib.pyplot as plt


plt.plot(x, y)
plt.title("Simple Line Chart")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show()
EXAMPLE

 Example code:-

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()
MARKERS

 You can use the keyword argument marker to emphasize each point with a specified
marker:

Example code:
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o')


plt.show()
MARKER REFERENCE

'o' Circle
'*' Star
'.' Point
',' Pixel
'x' X
'X' X (filled)
'+' Plus
'P' Plus (filled)
's' Square
'D' Diamond
FORMAT STRINGS FMT

 You can also use the shortcut string notation parameter to specify the marker.
 This parameter is also called fmt, and is written with this syntax:

Example code:
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, 'o:r')
plt.show()
TYPES OF CHARTS

 Line Chart:-
 Example code:-
 import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linestyle = 'dotted')


plt.show()
BAR CHART

 Example code:-

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()
HORIZONTAL BARS

 Example code:-
 import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y)
plt.show()
BAR COLOR

 The bar() and barh() take the keyword argument color to set the color of the bars:

Example code:-
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y, color = "red")


plt.show()
BAR WIDTH

 The bar() takes the keyword argument width to set the width of the bars:

Example code:-
 Draw 4 very thin bars:
 import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y, width = 0.1)


plt.show()
BAR HEIGHT

 The barh() takes the keyword argument height to set the height of the bars:

Example code:-
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y, height = 0.1)


plt.show()
HISTOGRAM

 Example code:-

import numpy as np

x = np.random.normal(170, 10, 250)

print(x)
PIE CHART

 Example code:-

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()
SCATTER PLOT

 Example code:-
 import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

plt.scatter(x, y)
plt.show()
WHAT IS TKINTER?

• Tkinter is a Python wrapper around Tcl/Tk, a GUI toolkit developed in the 1990s.
• It allows Python developers to create windows, dialogs, buttons, menus, textboxes, and
other interface elements.
• It’s built into Python, so you don’t need to install anything extra (tkinter module is included
in standard Python distribution).
KEY FEATURES

 Cross-platform: Works on Windows, macOS, and Linux.


 Lightweight: Good for simple to moderately complex GUI applications.
 Event-driven: Uses event loops to respond to user actions (clicks, key presses, etc.).
BASIC EXAMPLE
import tkinter as tk

# Create the main window


root = tk.Tk()
root.title("Hello Tkinter")
root.geometry("300x200")

# Create a label widget


label = tk.Label(root, text="Welcome to Tkinter!")
label.pack(pady=20)

# Create a button that closes the app


button = tk.Button(root, text="Close", command=root.destroy)
button.pack()

# Start the event loop


COMMON WIDGETS

Widget Description
Label Displays text or images
Button A clickable button
Entry A single-line text box
Text A multi-line text area
Frame A container for organizing widgets
Checkbutton, Radiobutton Selection controls
Canvas Drawing shapes, images, etc.
Menu Drop-down menus
BUTTON

 import tkinter as tk

 r = tk.Tk()
 r.title('Counting Seconds')
 button = tk.Button(r, text='Stop',
width=25, command=r.destroy)
 button.pack()
 r.mainloop()
ENTRY

 from tkinter import *

 master = Tk()
 Label(master, text='First Name').grid(row=0)
 Label(master, text='Last Name').grid(row=1)
 e1 = Entry(master)
 e2 = Entry(master)
 e1.grid(row=0, column=1)
 e2.grid(row=1, column=1)
 mainloop()
CHECKBUTTON

 from tkinter import *

 master = Tk()
 var1 = IntVar()
 Checkbutton(master, text='male',
variable=var1).grid(row=0, sticky=W)
 var2 = IntVar()
 Checkbutton(master, text='female',
variable=var2).grid(row=1, sticky=W)
 mainloop()
RADIOBUTTON

from tkinter import *

root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v,
value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v,
value=2).pack(anchor=W)
mainloop()

You might also like