0% found this document useful (0 votes)
18 views24 pages

Unit VTH Python Packages

The document provides an overview of Python packages, focusing on Tkinter and NumPy. Tkinter is a standard GUI library for creating desktop applications with various widgets, while NumPy is an open-source library for numerical computations, supporting multi-dimensional arrays and high-level mathematical functions. The document includes installation instructions, examples of creating GUI applications, and basic operations with NumPy arrays.

Uploaded by

arpitdd15
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)
18 views24 pages

Unit VTH Python Packages

The document provides an overview of Python packages, focusing on Tkinter and NumPy. Tkinter is a standard GUI library for creating desktop applications with various widgets, while NumPy is an open-source library for numerical computations, supporting multi-dimensional arrays and high-level mathematical functions. The document includes installation instructions, examples of creating GUI applications, and basic operations with NumPy arrays.

Uploaded by

arpitdd15
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

Unit Vth :Python Packages

Tkinter: Tkinter is a standard Python GUI (Graphical User Interface)


library that provides a set of tools and widgets to create desktop applications
with graphical interfaces. The name “Tkinter” comes from “Tk interface“,
referring to the Tk GUI toolkit that Tkinter is based on. Tkinter provides a way
to create windows, buttons, labels, text boxes, and other GUI components to
build interactive applications.
Tkinter uses:
1. Creating windows and dialog boxes: Tkinter can be used to create
windows and dialog boxes that allow users to interact with your program.
These can be used to display information, gather input, or present options
to the user.
2. Building a GUI for a desktop application: Tkinter can be used to create
the interface for a desktop application, including buttons, menus, and
other interactive elements.
3. Adding a GUI to a command-line program: Tkinter can be used to add
a GUI to a command-line program, making it easier for users to interact
with the program and input arguments.
4. Creating custom widgets: Tkinter includes a variety of built-in widgets,
such as buttons, labels, and text boxes, but it also allows you to create
your own custom widgets.
5. Prototyping a GUI: Tkinter can be used to quickly prototype a GUI,
allowing you to test and iterate on different design ideas before
committing to a final implementation.
Widgets in Tkinter?
In Tkinter, a widget is essentially a graphical component that the user can
interact with. They can range from simple elements like buttons and labels to
more complex ones like text entry fields, listboxes, and canvases. Each
widget serves a specific purpose and can be customized to fit the design and
functionality requirements of your application.
How Do Tkinter Widgets Work? Widgets are typically added to the
application’s window or frames using layout managers like pack(), grid(), or
place(), which determine their position and size within the interface.
Example-1:

# Python tkinter hello world program


from tkinter import *
root = Tk()
a = Label(root, text ="Hello World")
[Link]()
[Link]()
Output:

Example-2;
from tkinter import *
#or import tkinter as Tk
# create root window
root = Tk()
# frame inside root window
frame = Frame(root)

# geometry method
[Link]()
# button inside frame which is # inside root
button = Button(frame, text='Geek')
[Link]()
# Tkinter event loop
[Link]()
Output:

Where: root=Tk() # This automatically creates a graphical window with the


title bar, minimize, maximize and close buttons.
pack() : This tells it to size itself to fit the given text, and make itself [Link]
just tells the geometry manager to put widgets in the same row or column.
[Link]() : This method says to take all the widgets and objects we
created, render them on our screen, and respond to any interactions.
Tk() function to create a root window,

Tkinter Widget Basics


Tkinter supports the below mentioned core widgets –
Label Display static text or images.

Button It is used to add buttons to your application

Entry It is used to input single line text entry from user

Frame It is used as container to hold and organize the widgets

It is used to implement one-of-many selection as it allows only


RadioButton
one option to be selected

Checkbutton Create checkboxes for boolean options.

ListBox Display a list of items for selection.

Scrollbar Add scrollbars to widgets like Listbox.

Menu It is used to create all kinds of menu used by an application

Canvas Draw shapes, lines, text, and images.

Tkinter Widget Intermidate


Widgets Description

Text Create a multiline text input with advanced editing capabilities.

ComboBox Provide a dropdown list with editable text entry.


Widgets Description

Scale Create a scale widget for selecting values within a range.

TopLevel Create additional windows/dialogs.

Message Display simple messages or notifications.

MenuButton Create a button that opens a menu.

ProgressBar Show progress of a task.

SpinBox Provide a numerical input with up/down arrows.

Tkinter Widget Advance


Widgets Description

ScrolledText Create a text widget with built-in scrollbars.

Treeview Display hierarchical data in a tree-like structure.

MessageBox Display dialog boxes for messages, warnings, etc.

Treeview Scrollbar Add scrollbars to Treeview widgets.

Geometry Management
Creating a new widget doesn’t mean that it will appear on the screen. To
display it, we need to call a special method: either grid, pack(example
above), or place.
Method Description

pack() The Pack geometry manager packs widgets in rows or columns.

The Grid geometry manager puts the widgets in a 2-dimensional table.


grid() The master widget is split into a number of rows and columns, and each
“cell” in the resulting table can hold a widget.
Method Description

The Place geometry manager is the simplest of the three general


geometry managers provided in Tkinter.
place()
It allows you explicitly set the position and size of a window, either in
absolute terms, or relative to another window.

Creating a Button using Tkinter:


import tkinter as tk
def button_clicked():
print("Button clicked!")
root = [Link]()
# Creating a button with specified options
button = [Link](root,
text="Click Me",
command=button_clicked,
activebackground="blue",
activeforeground="white",
anchor="center",
bd=3,
bg="lightgray",
cursor="hand2",
disabledforeground="gray",
fg="black",
font=("Arial", 12),
height=2,
highlightbackground="black",
highlightcolor="green",
highlightthickness=2,
justify="center",
overrelief="raised",
padx=10,
pady=5,
width=15,
wraplength=100)
[Link](padx=20, pady=20)
[Link]()
Output:
Example-1: Create First GUI Application Using Tkinter:
# Import Module
from tkinter import * # import tkinter as tk
# create root window
root = Tk()
# root window title and dimension
[Link](“Welcome to GeekForGeeks”)
# Set geometry(widthxheight)
[Link](„350x200‟)
# adding a label to the root window
lbl = Label(root, text = “Are you a Geek?”)
[Link]()
# adding Entry Field
txt = Entry(root, width=10)
[Link](column =1, row =0)
# function to display user text when # button is clicked
def clicked():
res = “You wrote” + [Link]()
[Link](text = res)
# button widget with red color text inside
btn = Button(root, text = “Click me” ,
fg = “red”, command=clicked)
# Set Button Grid
[Link](column=2, row=0)
# Execute Tkinter
[Link]()

Output:
Example-2: Simple GUI calculator using Tkinter

# Python program to create a simple GUI calculator using Tkinter


# import everything from tkinter module
from tkinter import *
# globally declare the expression variable
expression = ""
# Function to update expression in the text entry box
def press(num):
# point out the global expression variable
global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
[Link](expression)
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used for handling the errors like zero
# division error etc.
# Put that code inside the try block which may generate the error
try:

global expression
# eval function evaluate the expression and str function
#convert the result into string
total = str(eval(expression))
[Link](total)

# initialize the expression variable by empty string


expression = ""
# if error is generate then handle by the except block
except:
[Link](" error ")
expression = ""
# Function to clear the contents of text entry box
def clear():
global expression
expression = ""
[Link]("")
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
[Link](background="light green")
# set the title of GUI window
[Link]("Simple Calculator")
# set the configuration of GUI window
[Link]("270x150")
# StringVar() is the variable class
# we create an instance of this class
equation = StringVar()
# create the text entry box for showing the expression
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing the widgets at respective
positions
# in table like structure .
expression_field.grid(columnspan=4, ipadx=70)
# create a Buttons and place at a particular
# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1,
width=7)
[Link](row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='red',
command=lambda: press(2), height=1,
width=7)
[Link](row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='red',
command=lambda: press(3), height=1,
width=7)
[Link](row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='red',
command=lambda: press(4), height=1,
width=7)
[Link](row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='red',
command=lambda: press(5), height=1,
width=7)
[Link](row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='red',
command=lambda: press(6), height=1,
width=7)
[Link](row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='red',
command=lambda: press(7), height=1,
width=7)
[Link](row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='red',
command=lambda: press(8), height=1,
width=7)
[Link](row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='red',
command=lambda: press(9), height=1,
width=7)
[Link](row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='red',
command=lambda: press(0), height=1,
width=7)
[Link](row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='red',
command=lambda: press("+"), height=1, width=7)
[Link](row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='red',
command=lambda: press("-"), height=1, width=7)
[Link](row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='red',
command=lambda: press("*"), height=1,
width=7)
[Link](row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='red',
command=lambda: press("/"), height=1,
width=7)
[Link](row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='red',
command=equalpress, height=1, width=7)
[Link](row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='red',
command=clear, height=1, width=7)
[Link](row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='red',
command=lambda: press('.'), height=1,
width=7)
[Link](row=6, column=0)
# start the GUI
[Link]()
NumPy: NumPy stands for Numerical Python, is an open-source Python library that
provides support for large, multi-dimensional arrays and matrices. It also have a
collection of high-level mathematical functions to operate on arrays. It was
created by Travis Oliphant in 2005.
Installation of NumPy: pip install numpy
Arrays in NumPy:
NumPy’s main object is the homogeneous multidimensional array.
 It is a table of elements (usually numbers), all of the same type, indexed
by a tuple of positive integers.
 In NumPy, dimensions are called axes. The number of axes is rank.
 NumPy’s array class is called ndarray. It is also known by the alias array.
Example: The first axis (dimension) is of length 2, i.e., the number of
rows, and the second axis (dimension) is of length 3, i.e., the number of
columns. The overall shape of the array can be represented as (2, 3)
import numpy as np

# Creating array object


arr = [Link]( [[ 1, 2, 3],
[ 4, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", [Link])
# Printing shape of array
print("Shape of array: ", [Link])
# Printing size (total number of elements) of array
print("Size of array: ", [Link])
# Printing type of elements in array
print("Array stores elements of type: ", [Link])
Output: Array is of type: <class '[Link]'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64
1. Create NumPy Array with List and Tuple:
import numpy as np
# Creating array from list with type float
a = [Link]([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)
# Creating array from tuple
b = [Link]((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)
Output: Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]
Array created using passed tuple:
[1 3 2]
2. Create Array of Fixed Size:[Link], [Link], [Link], [Link], etc.
# Creating a 3X4 array with all zeros
c = [Link]((3, 4))
print ("An array initialized with all zeros:\n", c)
# Create a constant value array of complex type
d = [Link]((3, 3), 6, dtype = 'complex')
print ("An array initialized with all 6s."
"Array type is complex:\n", d)
# Create an array with random values
e = [Link]((2, 2))
print ("A random array:\n", e)
output: An array initialized with all zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized with all [Link] type is complex:
[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]
A random array:
[[0.15471821 0.47506745]
[0.03637972 0.15772238]]
3. Create Using arange() Function: This function returns evenly spaced values
within a given interval. Step size is specified.
# Create a sequence of integers
# from 0 to 30 with steps of 5
f = [Link](0, 30, 5)
print ("A sequential array with steps of 5:\n", f)
Output: A sequential array with steps of 5:
[ 0 5 10 15 20 25]
4. Create Using linspace() Function: It returns evenly spaced values within a
given interval
# Create a sequence of 10 values in range 0 to 5
g = [Link](0, 5, 10)
print ("A sequential array with 10 values between
"0 and 5:\n", g)
Output: A sequential array with 10 values between0 and 5:
[0. 0.55555556 1.11111111
1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]
5. Flatten Array: Flatten array: We can use flatten method to get a copy of the
array collapsed into one dimension. It accepts order argument. The default value is
????’ (for row-major order). Use ????’ for column-major order.
# Flatten array
arr = [Link]([[1, 2, 3], [4, 5, 6]])
flat_arr = [Link]()
print ("Original array:\n", arr)
print ("Fattened array:\n", flat_arr)
Output: Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]
NumPy Array Indexing: Just like lists in Python, NumPy arrays can be sliced. As
arrays can be multidimensional, you need to specify a slice for each dimension of the
array.
# Python program to demonstrate indexing in numpy
import numpy as np
# An exemplar array
arr = [Link]([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)
# Integer array indexing example
temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1),"
"(3, 0):\n", temp)
# boolean array indexing example
cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)
NumPy-Unary Operators:
Many unary operations are provided as a method of ndarray class. This includes sum,
min, max, etc. These functions can also be applied row-wise or column-wise by setting
an axis [Link]:
# Python program to demonstrate unary operators in numpy
import numpy as np
arr = [Link]([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", [Link]())
print ("Row-wise maximum elements:",
[Link](axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",
[Link](axis = 0))
# sum of array elements
print ("Sum of all array elements:",
[Link]())
# cumulative sum along each row
print ("Cumulative sum along each row:\n",
[Link](axis = 1))
Output: Largest element is: 9
Row-wise maximum elements: [6 7 9]
Column-wise minimum elements: [1 1 2]
Sum of all array elements: 38
Cumulative sum along each row:
[[ 1 6 12]
[ 4 11 13]
[ 3 4 13]]
NumPy – Binary Operators:
These operations apply to the array elementwise and a new array is created. You can
use all basic arithmetic operators like +, -, /, etc.
# Python program to demonstrate binary operators in Numpy
import numpy as np
a = [Link]([[1, 2],
[3, 4]])
b = [Link]([[4, 3],
[2, 1]])
# add arrays
print ("Array sum:\n", a + b)
# multiply arrays (elementwise multiplication)
print ("Array multiplication:\n", a*b)
# matrix multiplication
print ("Matrix multiplication:\n", [Link](b))
NumPy Sorting Arrays:
# Python program to demonstrate sorting in numpy
import numpy as np
a = [Link]([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
# sorted array
print ("Array elements in sorted order:\n",
[Link](a, axis = None))
# sort array row-wise
print ("Row-wise sorted array:\n",
[Link](a, axis = 1))
# specify sort algorithm
print ("Column wise sort by applying merge-sort:\n",
[Link](a, axis = 0, kind = 'mergesort'))
# Example to show sorting of structured array # set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]
# Values to be put in array
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = [Link](values, dtype = dtypes)
print ("\nArray sorted by names:\n",
[Link](arr, order = 'name'))
print ("Array sorted by graduation year and then cgpa:\n",
[Link](arr, order = ['grad_year', 'cgpa']))
Appending Values at the End of an NumPy Array:
# importing the module
import numpy as np
# creating an array
arr = [Link]([1, 8, 3, 3, 5])
print('Original Array : ', arr)
# appending to the array
arr = [Link](arr, [7])
print('Array after appending : ', arr)
Output: Original Array : [1 8 3 3 5]
Array after appending : [1 8 3 3 5
1. Appending Another Array at the End of a 1D Array:
# importing the module
import numpy as np
# creating an array
arr1 = [Link]([1, 2, 3])
print('First array is : ', arr1)
# creating another array
arr2 = [Link]([4, 5, 6])
print('Second array is : ', arr2)
# appending arr2 to arr1
arr = [Link](arr1, arr2)
print('Array after appending : ', arr)
O/P: Array after appending : [1 2 3 4 5 6]
2. Appending Values at the End Using Concatenation:
import numpy as np
arr1 = [Link]([[1, 2], [3, 4]])
arr2 = [Link]([[5, 6]])
combined = [Link]((arr1, arr2), axis=0)
print(combined)
o/p: [[1 2]
[3 4]
[5 6]]
3. Appending with a Different Array Type:
import numpy as np
arr = [Link]([1, 2, 3])
arr_float = [Link]([4.0, 5.0])
combined = [Link](arr, arr_float)
print(combined) # Output: [1. 2. 3. 4. 5.]
4. Appending Using List Comprehension and [Link]:
# importing the module
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
values_to_append = [[Link]([6, 7]), [Link]([8, 9])]
combined = [Link]([arr] + values_to_append)
print(combined)
O/P: [1 2 3 4 5 6 7 8 9]
[Link] Values at the End of the N-Dimensional Array:
import numpy as np
# create an array
arr = [Link](1, 13).reshape(2, 6)
print('Original Array')
print(arr, '\n')
# create another array which is to be appended column-wise
col = [Link](5, 11).reshape(1, 6)
print('Array to be appended column wise')
print(col)
arr_col = [Link](arr, col, axis=0)
print('Array after appending the values column wise')
print(arr_col, '\n')
# create an array which is to be appended row wise
row = [Link]([1, 2]).reshape(2, 1)
print('Array to be appended row wise',row)
arr_row = [Link](arr, row, axis=1)
print('Array after appending the values row wise', arr_row)
O/P:Original Array
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Array to be appended column wise
[[ 5 6 7 8 9 10]]
Array after appending the values column wise
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[ 5 6 7 8 9 10]]
Array to be appended row wise
[[1]
[2]]
Array after appending the values row wise
[[ 1 2 3 4 5 6 1]
[ 7 8 9 10 11 12 2]]
Matplotlib: Matplotlib is a powerful plotting library in Python used for creating
static, animated, and interactive visualizations. Matplotlib’s primary purpose is
to provide users with the tools and functionality to represent data graphically

Different Types of Plots in Matplotlib:


 Line Graph
 Stem Plot
 Bar chart
 Histograms
 Scatter Plot
 Stack Plot
 Box Plot
 Pie Chart
 Violin Plot
 3D Plot
Installing Matplotlib: pip install matplotlib
Pyplot in Matplotlib: Pyplot is a Matplotlib module that provides a
MATLAB-like interface
Parameters:
 plot(x, y): plot x and y using default line style and color.
 [Link]([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from
minimum to maximum values
 plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2,
markersize=12):
x and y co-ordinates are marked using circular markers of size 12 and
green color line with — style of width 2
 [Link](‘X-axis’): names x-axis
 [Link](‘Y-axis’): names y-axis
 plot(x, y, label = ‘Sample line ‘): plotted Sample Line will be displayed
as a legend
 [Link]([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from
minimum to maximum values
 plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2,
markersize=12):
x and y co-ordinates are marked using circular markers of size 12 and
green color line with — style of width 2
 [Link](‘X-axis’): names x-axis
 [Link](‘Y-axis’): names y-axis
 plot(x, y, label = ‘Sample line ‘): plotted Sample Line will be displayed
as a legend
Example: Simple plot
# Python program to show plot function
import [Link] as plt
[Link]([1, 2, 3, 4], [1, 4, 9, 16])
[Link]([0, 6, 0, 20])
[Link]()
Linear Plot using [Link]:
# Python Program to illustrate Linear Plotting
import [Link] as plt
year = [1972, 1982, 1992, 2002, 2012]
e_india = [100.6, 158.61, 305.54, 394.96, 724.79]
e_bangladesh = [10.5, 25.21, 58.65,119.27, 274.87]
# formatting of line style and # plotting of co-ordinates
[Link](year, e_india, color ='blue',marker ='o', markersize = 12, label ='India')
[Link](year, e_bangladesh, color ='black',linestyle ='dashed', linewidth = 2,label
='Bangladesh')
[Link]('Years')
[Link]('Power consumption in kWh')
[Link]('Electricity consumption per \
capita of India and Bangladesh')
[Link]()
[Link]()
Scatter Plot with Color Mapping:
import [Link] as plt
import numpy as np
# Generate random data
[Link](42)
x = [Link](50)
y = [Link](50)
colors = [Link](50)
# Create a scatter plot with color mapping
[Link](x, y, c=colors, cmap='viridis', s=100, alpha=0.8)
# Add color bar for reference
cbar = [Link]()
cbar.set_label('Color Value')
# Set plot title and labels
[Link]('Scatter Plot with Color Mapping')
[Link]('X-axis')
[Link]('Y-axis')
# Display the plot
[Link]()

Creating a bar plot:syntax


[Link](x, height, width, bottom, align)
import numpy as np
import [Link] as plt
# set width of bar
barWidth = 0.25
fig = [Link](figsize =(12, 8))
# set height of bar
IT = [12, 30, 1, 8, 22]
ECE = [28, 6, 16, 5, 10]
CSE = [29, 3, 24, 25, 17]
# Set position of bar on X axis
br1 = [Link](len(IT))
br2 = [x + barWidth for x in br1]
br3 = [x + barWidth for x in br2]
# Make the plot
[Link](br1, IT, color ='r', width = barWidth, edgecolor ='grey', label ='IT')
[Link](br2, ECE, color ='g', width = barWidth, edgecolor ='grey', label ='ECE')
[Link](br3, CSE, color ='b', width = barWidth, edgecolor ='grey', label ='CSE')
# Adding Xticks
[Link]('Branch', fontweight ='bold', fontsize = 15)
[Link]('Students passed', fontweight ='bold', fontsize = 15)
[Link]([r + barWidth for r in range(len(IT))],
['2015', '2016', '2017', '2018', '2019'])
[Link]()
[Link]()

Plot a pie chart:


# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
fig = [Link](figsize=(10, 7))
[Link](data, labels=cars)
# show plot
[Link]()

Histogram plot in matplot:


import [Link] as plt
import numpy as np
# Generate random data for the histogram
data = [Link](1000)
# Plotting a basic histogram
[Link](data, bins=30, color='skyblue', edgecolor='black')
# Adding labels and title
[Link]('Values')
[Link]('Frequency')
[Link]('Basic Histogram')
# Display the plot
[Link]()
Pandas: The Pandas library is used for data manipulation and analysis. Pandas is well-
suited for working with tabular data, such as spreadsheets or SQL [Link] is built on top of
the NumPy library which means that a lot of the structures of NumPy are used or
replicated in Pandas.
Installation: pip install pandas
Here is a list of things that we can do using Pandas.
 Data set cleaning, merging, and joining.
 Easy handling of missing data (represented as NaN) in floating point as well as
non-floating point data.
 Columns can be inserted and deleted from DataFrame and higher-dimensional
objects.
 Powerful group by functionality for performing split-apply-combine operations on
data sets.
 Data Visualization.
Data Structures in Pandas Library:
Pandas generally provide two data structures for manipulating data. They are:
 Series
 DataFrame
Series: A Pandas Series is a one-dimensional labeled array capable of holding data
of any type (integer, string, float, Python objects, etc.). The axis labels are collectively
called indexes.
The Pandas Series is nothing but a column in an Excel sheet. Labels need not be
unique but must be of a hashable type. Pandas series is created by loading the
datasets from existing storage (which can be a SQL database, a CSV file, or
an Excel file).
Pandas Series can be created from lists, dictionaries, scalar values, etc.
Example: Creating a series using the Pandas Library.
import pandas as pd
import numpy as np
# Creating empty series
ser = [Link]()
print("Pandas Series: ", ser)
# simple array
data = [Link](['s', 'm', 's', 'L', 'K',’O’])
ser = [Link](data)
print("Pandas Series:\n", ser)
O/P: Pandas Series: Series([], dtype: float64)
Pandas Series:
0 s
1 m
2 s
3 L
4 K
5 O
dtype: object
Pandas DataFrame:
Pandas DataFrame is a two-dimensional data structure with labeled axes (rows and
columns).
Creating DataFrame:
Pandas DataFrame is created by loading the datasets from existing storage (which
can be a SQL database, a CSV file, or an Excel file).
Pandas DataFrame can be created from lists, dictionaries, a list of dictionaries,
etc.
Example -1: Creating a DataFrame Using the Pandas Library:
import pandas as pd
# Calling DataFrame constructor
df = [Link]()
print(df)
# list of strings
lst = ['S', 'M', 'S', 'is', 'in', 'L', 'K',’O’]
# Calling DataFrame constructor on list
df = [Link](lst)
print(df)
Empty DataFrame
Columns:[]
Index: []
0
0 S
1 M
2 S
3 is
4 in
5 L
6 K
7 O
Example-2:
# importing pandas as pd
import pandas as pd
# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
'degree': ["MBA", "BCA", "[Link]", "MBA"],
'score':[90, 40, 80, 98]}
df = [Link](dict)
print(df)

You might also like