0% found this document useful (0 votes)
74 views25 pages

Unit 5

The document provides information about using Tkinter to create graphical user interfaces in Python desktop applications. Tkinter is Python's standard library for building GUI apps. It discusses how to create a basic empty Tkinter window using import statements and the Tk() function. It also provides a simple example Tkinter code sample and explains each line.

Uploaded by

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

Unit 5

The document provides information about using Tkinter to create graphical user interfaces in Python desktop applications. Tkinter is Python's standard library for building GUI apps. It discusses how to create a basic empty Tkinter window using import statements and the Tk() function. It also provides a simple example Tkinter code sample and explains each line.

Uploaded by

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

Python Tkinter Tutorial

Python provides the standard library Tkinter for creating the graphical user interface for
desktop based applications.

Developing desktop based applications with python Tkinter is not a complex task. An empty
Tkinter top-level window can be created by using the following steps.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer
screen.

Example

1. # !/usr/bin/python3  
2. from tkinter import *  
3. #creating the application main window.   
4. top = Tk()  
5. #Entering the event main loop  
6. top.mainloop()  

Output:

from tkinter import *


from tkinter import ttk
window = Tk()
window.title("Welcome to TutorialsPoint")
window.geometry('325x250')
window.configure(background = "gray")
ttk.Button(window, text="Hello, Tkinter").grid()
window.mainloop()

Let's understand the above lines of code −


 Firstly we import all the modules we need, we have imported ttk and * (all)
from tkinter library.
 To create the main window of our application, we use Tk class.
 window.title(), give the title to our Window app.
 window.geometry(), set the size of the window and window.configure(), set its
background color.
 ttk.Button() makes a button.
 ttk.Button(window, text="Hello, Tkinter").grid() – window means Tk so it
shows in the window we created, text- will display the text in the window and
grid will make it in a grid.
 Window.mainloop(), this function calls the endless loop of the window, so will
remain open till the user closes it.

Tkinter widgets

There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications.

S Widget Description
N

1 Button The Button is used to add various kinds of buttons to the python
application.

2 Canvas The canvas widget is used to draw the canvas on the window.

3 Checkbutton The Checkbutton is used to display the CheckButton on the


window.

4 Entry The entry widget is used to display the single-line text field to the
user. It is commonly used to accept user values.

5 Frame It can be defined as a container to which, another widget can be


added and organized.

6 Label A label is a text used to display some message or information


about the other widgets.

7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.

9 Menu It is used to add menu items to the user.

10 Message The Message widget is used to display the message-box to the


user.

11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is


provided with various options and the user can select only one
option among them.

12 Scale It is used to provide the slider to the user.

13 Scrollbar It provides the scrollbar to the user so that the user can scroll the
window up and down.

14 Text It is different from Entry because it provides a multi-line text field


to the user so that the user can write the text and edit the text
inside it.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindow It is like a container widget that contains horizontal or vertical


panes.

17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the desktop


based applications.

Python Tkinter Geometry

The Tkinter geometry specifies the method by using which, the widgets are represented on
display. The python Tkinter provides the following geometry methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method


The pack() widget is used to organize widget in the block. The positions widgets added to the
python application using the pack() method can be controlled by using the various options
specified in the method call.

However, the controls are less and widgets are generally added in the less organized manner.

The syntax to use the pack() is given below.

syntax

1. widget.pack(options)  

A list of possible options that can be passed in pack() is given below.

o expand: If the expand is set to true, the widget expands to fill any space.
o Fill: By default, the fill is set to NONE. However, we can set it to X or Y to
determine whether the widget contains any extra space.
o size: it represents the side of the parent to which the widget is to be placed on the
window.

Example

# !/usr/bin/python3  
from tkinter import *  
parent = Tk()  
redbutton = Button(parent, text = "Red", fg = "red")  
redbutton.pack( side = LEFT)  
greenbutton = Button(parent, text = "Black", fg = "black")  
greenbutton.pack( side = RIGHT )  
bluebutton = Button(parent, text = "Blue", fg = "blue")  
bluebutton.pack( side = TOP )  
blackbutton = Button(parent, text = "Green", fg = "red")  
blackbutton.pack( side = BOTTOM)  
parent.mainloop()  

Output:
Python Tkinter grid() method

The grid() geometry manager organizes the widgets in the tabular form. We can specify the
rows and columns as the options in the method call. We can also specify the column span
(width) or rowspan(height) of a widget.

This is a more organized way to place the widgets to the python application. The syntax to
use the grid() is given below.

Syntax

widget.grid(options)  

A list of possible options that can be passed inside the grid() method is given below.

o Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to which, the column
is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
o padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
o row
The row number in which the widget is to be placed. The topmost row is represented
by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the widget is
expanded.
o Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the
widget inside the cell. It may be the concatenation of the sticky letters representing
the position of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.

Example

# !/usr/bin/python3  
from tkinter import *  
parent = Tk()  
name = Label(parent,text = "Name").grid(row = 0, column = 0)  
e1 = Entry(parent).grid(row = 0, column = 1)  
password = Label(parent,text = "Password").grid(row = 1, column = 0)  
e2 = Entry(parent).grid(row = 1, column = 1)  
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)  
parent.mainloop()  

Output:

Python Tkinter place() method

The place() geometry manager organizes the widgets to the specific x and y coordinates.

Syntax

1. widget.place(options)  

A list of possible options is given below.

o Anchor: It represents the exact position of the widget within the container. The
default value (direction) is NW (the upper left corner)
o bordermode: The default value of the border type is INSIDE that refers to ignore the
parent's inside the border. The other option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the
fraction of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the
horizontal and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.
Example

# !/usr/bin/python3  
from tkinter import *  
top = Tk()  
top.geometry("400x250")  
name = Label(top, text = "Name").place(x = 30,y = 50)  
email = Label(top, text = "Email").place(x = 30, y = 90)  
password = Label(top, text = "Password").place(x = 30, y = 130)  
e1 = Entry(top).place(x = 80, y = 50)  
e2 = Entry(top).place(x = 80, y = 90)  
e3 = Entry(top).place(x = 95, y = 130)  
top.mainloop()  

Output:

Python Tkinter Button

PlayNext
Unmute

Current Time 0:00

Duration 18:10
Loaded: 0.37%
 
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

The button widget is used to add various types of buttons to the python application. Python
allows us to configure the look of the button according to our requirements. Various options
can be set or reset depending upon the requirements.

We can also associate a method or function with a button which is called when the button is
pressed.

The syntax to use the button widget is given below.

Syntax

1. W = Button(parent, options)   

A list of possible options is given below.

SN Option Description

1 activebackground It represents the background of the button when the mouse


hover the button.

2 activeforeground It represents the font color of the button when the mouse hover
the button.

3 Bd It represents the border width in pixels.

4 Bg It represents the background color of the button.

5 Command It is set to the function call which is scheduled when the


function is called.

6 Fg Foreground color of the button.

7 Font The font of the button text.

8 Height The height of the button. The height is represented in the


number of text lines for the textual lines or the number of pixels
for the images.

10 Highlightcolor The color of the highlight when the button has the focus.

11 Image It is set to the image displayed on the button.

12 justify It illustrates the way by which the multiple text lines are
represented. It is set to LEFT for left justification, RIGHT for
the right justification, and CENTER for the center.

13 Padx Additional padding to the button in the horizontal direction.

14 pady Additional padding to the button in the vertical direction.

15 Relief It represents the type of the border. It can be SUNKEN,


RAISED, GROOVE, and RIDGE.

17 State This option is set to DISABLED to make the button


unresponsive. The ACTIVE represents the active state of the
button.

18 Underline Set this option to make the button text underlined.

19 Width The width of the button. It exists as a number of letters for


textual buttons or pixels for image buttons.

20 Wraplength If the value is set to a positive number, the text lines will be
wrapped to fit within this length.

Example

1. #python application to create a simple button    
from tkinter import *   
top = Tk()  
top.geometry("200x100")  
b = Button(top,text = "Simple")  
b.pack()  
top.mainaloop()  

Output:

Example

from tkinter import *   
 top = Tk()  
  
top.geometry("200x100")  
  
def fun():  
    messagebox.showinfo("Hello", "Red Button clicked")  
  
b1 = Button(top,text = "Red",command = fun,activeforeground = "red",activebackground = "
pink",pady=10) 
b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=1
0)  
  
b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink",pady 
= 10)  
  
b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",pad
y = 10)  
  
b1.pack(side = LEFT)  
  
b2.pack(side = RIGHT)  
  
b3.pack(side = TOP)  
  
b4.pack(side = BOTTOM)  
  
top.mainloop()  

Output:

Python Tkinter Canvas

The canvas widget is used to add the structured graphics to the python application. It is used
to draw the graph and plots to the python application. The syntax to use the canvas is given
below.
Syntax

1. w = canvas(parent, options)  

A list of possible options is given below.

SN Option Description

1 bd The represents the border width. The default width is 2.

2 bg It represents the background color of the canvas.

3 confine It is set to make the canvas unscrollable outside the scroll region.

4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.

5 height It represents the size of the canvas in the vertical direction.

6 highlightcolor It represents the highlight color when the widget is focused.

7 relief It represents the type of the border. The possible values are SUNKEN, RAIS
GROOVE, and RIDGE.

8 scrollregion It represents the coordinates specified as the tuple containing the area of the canva

9 width It represents the width of the canvas.

10 xscrollincremen If it is set to a positive value. The canvas is placed only to the multiple of this valu
t

11 xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the horiz
scrollbar.

12 yscrollincremen Works like xscrollincrement, but governs vertical movement.


t

13 yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the ve
scrollbar.

Example

from tkinter import *   
  
top = Tk()  
  
top.geometry("200x200")  
  
#creating a simple canvas  
c = Canvas(top,bg = "pink",height = "200")  
  
  
c.pack()  
  
top.mainloop()  

Example

from tkinter import *   
  top = Tk()  
  top.geometry("200x200")  
  
#creating a simple canvas  
c = Canvas(top,bg = "pink",height = "200")  
  c.pack()  
  top.mainloop()  

Output:

Example: Creating an arc

from tkinter import *   
  
top = Tk()  
  
top.geometry("200x200")  
  
#creating a simple canvas  
c = Canvas(top,bg = "pink",height = "200",width = 200)  
  
arc = c.create_arc((5,10,150,200),start = 0,extent = 150, fill= "white")  
  
c.pack()  
  
top.mainloop()  

Output:

Python – Packages

A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package. When a module from an external package is required
in a program, that package can be imported and its modules can be put to use.

We organize a large number of files in different folders and subfolders based on some
criteria, so that we can find and manage them easily. In the same way, a package in Python
takes the concept of the modular approach to next logical level. As you know,
a module can contain multiple objects, such as classes, functions, etc. A package can
contain one or more relevant modules. Physically, a package is actually a folder containing
one or more module files.

Let's create a package named mypackage, using the following steps:

 Create a new folder named D:\MyApp.


 Inside MyApp, create a subfolder with the name 'mypackage'.
 Create an empty __init__.py file in the mypackage folder.
 Using a Python-aware editor like IDLE, create modules greet.py and functions.py
with the following code:

greet.py
 Copy

def SayHello(name):
print("Hello ", name)
functions.py

 Copy

def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

That's it. We have created our package called mypackage. The following is a folder
structure:

Package Folder Structure

Importing a Module from a Package

Now, to test our package, navigate the command prompt to the MyApp folder and invoke
the Python prompt from there.

D:\MyApp>python

Import the functions module from the mypackage package and call its power() function.

>>> from mypackage import functions

>>> functions.power(3,2)

It is also possible to import specific functions from a module in the package.


>>> from mypackage.functions import sum

>>> sum(10,20)

30

>>> average(10,12)

Traceback (most recent call last):

File "<pyshell#13>", line 1, in <module>

NameError: name 'average' is not defined

5.2M

56

Wordpress vs custom website cms | Two Software Developer Career Path

__init__.py

The package folder contains a special file called __init__.py, which stores the package's
content. It serves two purposes:

1. The Python interpreter recognizes a folder as the package if it


contains __init__.py file.
2. __init__.py exposes specified resources from its modules to be imported.

An empty __init__.py file makes all functions from the above modules available when this
package is imported. Note that __init__.py is essential for the folder to be recognized by
Python as a package. You can optionally define functions from individual modules to be
made available.

 Note:

We shall also create another Python script in the MyApp folder and import the mypackage
package in it. It should be at the same level of the package to be imported.
The __init__.py file is normally kept empty. However, it can also be used to choose
specific functions from modules in the package folder and make them available for import.
Modify __init__.py as below:

__init__.py

 Copy

from .functions import average, power


from .greet import SayHello

The specified functions can now be imported in the interpreter session or another
executable script.

Create test.py in the MyApp folder to test mypackage.

test.py

 Copy

from mypackage import power, average, SayHello


SayHello()
x=power(3,2)
print("power(3,2) : ", x)

Note that functions power() and SayHello() are imported from the package and not from
their respective modules, as done earlier. The output of the above script is:

D:\MyApp>python test.py

Hello world

power(3,2) : 9

Install a Package Globally

Once a package is created, it can be installed for system-wide use by running the setup
script. The script calls setup() function from the setuptools module.

Let's install mypackage for system-wide use by running a setup script.

Save the following code as setup.py in the parent folder MyApp. The script calls
the setup() function from the setuptools module. The setup() function takes various
arguments such as name, version, author, list of dependencies, etc. The zip_safe argument
defines whether the package is installed in compressed mode or regular mode.
Example: setup.py

 Copy

from setuptools import setup


setup(name='mypackage',
version='0.1',
description='Testing installation of Package',
url='#',
author='auth',
author_email='[email protected]',
license='MIT',
packages=['mypackage'],
zip_safe=False)

Now execute the following command to install mypackage using the pip utility. Ensure


that the command prompt is in the parent folder, in this case D:\MyApp.

D:\MyApp>pip install mypackage

Processing d:\MyApp

Installing collected packages: mypack

Running setup.py install for mypack ... done

Successfully installed mypackage-0.1

Now mypackage is available for system-wide use and can be imported in any script or
interpreter.

D:\>python

>>> import mypackage

>>>mypackage.average(10,20)

15.0
>>>mypackage.power(10,2)

100

You may also want to publish the package for public use. PyPI (stands for Python Package
Index) is a repository of Python packages.
Visit https://packaging.python.org/distributing  to know more about the procedure of
uploading a package to PyPI.

NumPy and Pandas Tutorial – Data Analysis with Python

Python is increasingly being used as a scientific language. Matrix and vector manipulations
are extremely important for scientific computations. Both NumPy and Pandas have emerged
to be essential libraries for any scientific computation, including machine learning, in python
due to their intuitive syntax and high-performance matrix computation capabilities.

In this post, we will provide an overview of the common functionalities of NumPy and
Pandas. We will realize the similarity of these libraries with existing toolboxes in R and
MATLAB. This similarity and added flexibility have resulted in wide acceptance of python
in the scientific community lately. Topic covered in the blog are:

1. Overview of NumPy
2. Overview of Pandas
3. Using Matplotlib

This post is an excerpt from a live hands-on training conducted by CloudxLab on 25th
Nov 2017. It was attended by more than 100 learners around the globe. The participants were
from countries namely; United States, Canada, Australia, Indonesia, India, Thailand,
Philippines, Malaysia, Macao, Japan, Hong Kong, Singapore, United Kingdom, Saudi
Arabia, Nepal, & New Zealand.

What is NumPy?
NumPy stands for ‘Numerical Python’ or ‘Numeric Python’. It is an open source module of
Python which provides fast mathematical computation on arrays and matrices. Since, arrays
and matrices are an essential part of the Machine Learning ecosystem, NumPy along with
Machine Learning modules like Scikit-learn, Pandas, Matplotlib, TensorFlow, etc. complete
the Python Machine Learning Ecosystem.

NumPy provides the essential multi-dimensional array-oriented computing functionalities


designed for high-level mathematical functions and scientific computation. Numpy can be
imported into the notebook using

>>> import numpy as np

NumPy’s main object is the homogeneous multidimensional array. It is a table with same
type elements, i.e, integers or string or characters (homogeneous), usually integers. In
NumPy, dimensions are called axes. The number of axes is called the rank.

There are several ways to create an array in NumPy like np.array, np.zeros, no.ones, etc. Each
of them provides some flexibility.

Command to create an array Example

>>> a = np.array([1, 2, 3])


>>> type(a)
<type 'numpy.ndarray'>
np.array
>>> b = np.array((3, 4, 5))
>>> type(b)
<type 'numpy.ndarray'>

>>> np.ones( (3,4), dtype=np.int16 )  


array([[ 1,  1,  1,  1],
np.ones
      [ 1,  1,  1,  1],
      [ 1,  1,  1,  1]])

>>> np.full( (3,4), 0.11 )  


array([[ 0.11,  0.11,  0.11,  0.11],        
np.full
  [ 0.11,  0.11,  0.11,  0.11],        
  [ 0.11,  0.11,  0.11,  0.11]])

>>> np.arange( 10, 30, 5 )


array([10, 15, 20, 25])
np.arange
>>> np.arange( 0, 2, 0.3 )             
# it accepts float arguments
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])
>>> np.linspace(0, 5/3, 6)
np.linspace array([0. , 0.33333333 , 0.66666667 , 1. , 1.33333333
1.66666667])

>>> np.random.rand(2,3)
np.random.rand(2,3) array([[ 0.55365951,  0.60150511,  0.36113117],
      [ 0.5388662 ,  0.06929014,  0.07908068]])

>>> np.empty((2,3))
np.empty((2,3)) array([[ 0.21288689,  0.20662218,  0.78018623],
      [ 0.35294004,  0.07347101,  0.54552084]])
Some of the important attributes of a NumPy object are:

1. Ndim: displays the dimension of the array


2. Shape: returns a tuple of integers indicating the size of the array
3. Size: returns the total number of elements in the NumPy array
4. Dtype: returns the type of elements in the array, i.e., int64, character
5. Itemsize: returns the size in bytes of each item
6. Reshape: Reshapes the NumPy array

NumPy array elements can be accessed using indexing. Below are some of the useful
examples:

 A[2:5] will print items 2 to 4. Index in NumPy arrays starts from 0


 A[2::2] will print items 2 to end skipping 2 items
 A[::-1] will print the array in the reverse order
 A[1:] will print from row 1 to end

The session covers these and some important attributes of the NumPy array object in detail.

Vectors and Machine learning

Machine learning uses vectors. Vectors are one-dimensional arrays. It can be represented
either as a row or as a column array.

What are vectors? Vector quantity is the one which is defined by a magnitude and a direction.
For example, force is a vector quantity. It is defined by the magnitude of force as well as a
direction. It can be represented as an array [a,b] of 2 numbers = [2,180] where ‘a’ may
represent the magnitude of 2 Newton and 180 (‘b’) represents the angle in degrees.

Another example, say a rocket is going up at a slight angle: it has a vertical speed of 5,000
m/s, and also a slight speed towards the East at 10 m/s, and a slight speed towards the North
at 50 m/s. The rocket’s velocity may be represented by the following vector: [10, 50, 5000]
which represents the speed in each of x, y, and z-direction.

Similarly, vectors have several usages in Machine Learning, most notably to represent
observations and predictions.
For example, say we built a Machine Learning system to classify videos into 3 categories
(good, spam, clickbait) based on what we know about them. For each video, we would have a
vector representing what we know about it, such as: [10.5, 5.2, 3.25, 7.0]. This vector could
represent a video that lasts 10.5 minutes, but only 5.2% viewers watch for more than a
minute, it gets 3.25 views per day on average, and it was flagged 7 times as spam.

As you can see, each axis may have a different meaning. Based on this vector, our Machine
Learning system may predict that there is an 80% probability that it is a spam video, 18% that
it is clickbait, and 2% that it is a good video. This could be represented as the following
vector: class_probabilities = [0.8,0.18,0.02].

As can be observed, vectors can be used in Machine Learning to define observations and
predictions. The properties representing the video, i.e., duration, percentage of viewers
watching for more than a minute are called features. 

Since the majority of the time of building machine learning models would be spent in data
processing, it is important to be familiar to the libraries that can help in processing such data.

Pandas

Similar to NumPy, Pandas is one of the most widely used python libraries in data science. It
provides high-performance, easy to use structures and data analysis tools. Unlike NumPy
library which provides objects for multi-dimensional arrays, Pandas provides in-memory 2d
table object called Dataframe. It is like a spreadsheet with column names and row labels.

Hence, with 2d tables, pandas is capable of providing many additional functionalities like
creating pivot tables, computing columns based on other columns and plotting graphs. Pandas
can be imported into Python using:

>>> import pandas as pd

Some commonly used data structures in pandas are:

1. Series objects: 1D array, similar to a column in a spreadsheet


2. DataFrame objects: 2D table, similar to a spreadsheet
3. Panel objects: Dictionary of DataFrames, similar to sheet in MS Excel

Pandas Series object is created using pd.Series function. Each row is provided with an index
and by defaults is assigned numerical values starting from 0. Like NumPy, Pandas also
provide the basic mathematical functionalities like addition, subtraction and conditional
operations and broadcasting.
Pandas dataframe object represents a spreadsheet with cell values, column names, and row
index labels. Dataframe can be visualized as dictionaries of Series. Dataframe rows and
columns are simple and intuitive to access. Pandas also provide SQL-like functionality to
filter, sort rows based on conditions. For example,

>>> people_dict = { "weight": pd.Series([68, 83, 112],index=["alice", "bob", "charles"]),  


"birthyear": pd.Series([1984, 1985, 1992], index=["bob", "alice", "charles"], name="year"),

"children": pd.Series([0, 3], index=["charles", "bob"]),

"hobby": pd.Series(["Biking", "Dancing"], index=["alice", "bob"]),}

>>> people = pd.DataFrame(people_dict)

>>> people

>>> people[people["birthyear"] < 1990]

New columns and rows can be easily added to the dataframe. In addition to the basic
functionalities, pandas dataframe can be sorted by a particular column.

Dataframes can also be easily exported and imported from CSV, Excel, JSON, HTML and
SQL database. Some other essential methods that are present in dataframes are:

1. head(): returns the top 5 rows in the dataframe object


2. tail(): returns the bottom 5 rows in the dataframe
3. info(): prints the summary of the dataframe
4. describe(): gives a nice overview of the main aggregated values over each column

What is matplotlib?

Matplotlib is a 2d plotting library which produces publication quality figures in a variety of


hardcopy formats and interactive environments. Matplotlib can be used in Python scripts,
Python and IPython shell, Jupyter Notebook, web application servers and GUI toolkits.

matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB.


Majority of plotting commands in pyplot have MATLAB analogs with similar arguments. Let
us take a couple of examples:

Example 1: Plotting a line graph Example 2: Plotting a histogram

>>> import matplotlib.pyplot as plt >>> import matplotlib.pyplot as plt

>>> plt.plot([1,2,3,4]) >>> x =


[21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,3
6,37,18,49,50,100]
>>> plt.ylabel('some numbers')

>>> num_bins = 5
>>> plt.show()

>>> plt.hist(x, num_bins, facecolor='blue')

>>> plt.show()

You might also like