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

python notes sarang sir (1)

This document provides an introduction to Python, detailing its features, applications, and installation process on Windows. It also covers Jupyter Notebook usage, Python scripting with various modules, and an overview of the Numpy library for numerical computations. Key topics include Python's dynamic nature, object-oriented programming, and the efficient handling of arrays with Numpy.
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)
13 views24 pages

python notes sarang sir (1)

This document provides an introduction to Python, detailing its features, applications, and installation process on Windows. It also covers Jupyter Notebook usage, Python scripting with various modules, and an overview of the Numpy library for numerical computations. Key topics include Python's dynamic nature, object-oriented programming, and the efficient handling of arrays with Numpy.
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/ 24

UNIT 3

Introduction to python
 Python is a general purpose, dynamic, high level and interpreted
programming language.
 It supports object oriented programming approach to develop
application.
 It was designed by Guide Van Rossum in 1991.
 Python features-
1. Easy to learn & use.
2. Expressive language.
3. Interpreted language.
4. Cross-platform language.
5. Free and open source.
6. Dynamic memory allocation.
7. Large standard library.
 Python Applications-
 Web Applications
 Desktop GUI Applications
 Console based Application
 Scientific & numeric
 Audio or video-based Application
 3D CAD Application
 Image Processing Applications
 Software development

Installation on windows-
 Visit the link http://www.python.org to download the latest
version.
Step 1)- select the python version to download.
Step 2)- click on the install now.
[Double click the executable file, which is download.
Click on the Add path check box, if will set the python path
automatically]
Step 3)- Installation in process.
This set up is in process. All the python libraries packages and
other python default files will be installed in our system. Once the
installation is successful, the page will appear saying…
“setup was successful”.
Jupyter Notebook-
Step 4)- verifying the python Installation.
1) Go to start and search for ”cmd”.
2) Then type “python----version”.
3) If python is successful installed, then we can see the version
of the python installed.
4) If not installed , then if will print the error as ‘python’ is not
recognized as an internal or external command, operable
program or batch file.
Jupyter Notebook-
 Jupyter notebook is an open source web application that you can
use to create and share document that contain live code, equation,
visualizations and text.
 It supports over 40 programming languages, including python , R,
scala.
 Using Jupyter Notebook-
Step 1)-click the ‘start’ button on windows taskbar and select
‘Anacondas’
Step 2)- To enter a new program, click the ‘files’ tab, then click
‘New’ and then ‘python3’.
Step 3)- It open`s a new page click ‘untitled’ at the top of the page
and enter a new name for your program. Then click ‘Rename’ button.
Step 4)- Type the program code in the cell and click ‘Run’ to run the
code of the current cell.
Step 5)- We can enter code in the next cell and so on, In this manner,
we can run the program as block of code, one block at a time, when
the input is required, it will wait for yours input to enter.
The blue box around the cell indicate the command mode.
In[1]: import math
In[*]: num=float(input(“Enter a number”))
Enter a Number: 25
Fig:- Displaying the command mode.
Step 6)- Type the program in cells and run each cell to see the result
to save the program in jupyter save with extension .ipynb
Which indicate interactive python notebook file.
Step 7)- To reopen the program first enter into Jupyter Notebook : in
the ‘files tab’ find out program name and click on it.
Step 8)- To delete select file and then click delete bin symbol.

Python Scripting-
 Scripting is writing program to automate the task.
 The code line which you write they are interpreted rather than
compile so they are executed at runtime.
 Modules in python scripting.
1) Sys module
2) Os module
3) Math
4) Random
5) Date time

1) Sys module:-
 Sys module basically provides the information about the
constant function and method of python interpreter.
 It is basically responsible for controlling and interacting with
the interpreter.
 If you want to know any information on operating system or
version of python. For that you can use sys module.
Import sys
Print(sys.version)
(for printing version of python print(sys.argv) to show the
lists of arguments which is pass from command line to
program.
2) Os module:-
 It is used to interact with operating system.
 To print current working directory
Import os
Print(os.getcwd())
 To change directory
Import os
Os.chdir(“D:\\python\\New folder”)
Print(os.getcwd())
3) To add directory:-
 Os.mkdir(“D:\\python\\anagha”)
4) To remove directory:-
 Os.rmdir(“D:\\python\\anagha”)
5) To remove file:-
 Os.remove(“D:\\python\\abc.py”)
6) To split the path:-
 Print(os.path.split(“D:\\python\\anagha\\abc”)
O/P:- (“D:\\python\\anagha”,’abc’)
7) To check whether file exist:-
 Print(“os.path.exists(“D:\\python\\anagha\\abc.py”))
O/P:- true
3) Random Module:-
 To generate the random value
1) Rand int():- It generate the random number in range.
 Step size is not allowed in rand int() function.
Import random
N=random. rand int(2,8)
Print(n)
O/P:-2
4
6
8

2). Rand range()


 Randrange () function is similar to randint () but in randrange()
endpoint of range is executed and rand range () allow the step size.

3). Choice():-
 Choice () function is used to choose any element from the list.
Ex:- l=[20,30,40,50]
Lc=random choice(l)
Print(lc)
O/P:- 30
50

4). Random ():-


 It returns a random float number between 0 & 1.
Import random
r= random .random()
print(r)
O/P:- 0.3
0.4
0.91

5). Shuffle:-

 It takes the sequence and return the sequence in a random order.


l=[30,40,50,60]
random shuffle(l)
print(l)
O/P:- [40,50,60,30]
[60,30,50,40]

6). Uniform:-
 It return a random float number between two given parameters.
U=random uniform(3,9)
Print(4)
O/P:- 4.2
5.22

4). Datetime Module:-


 Strt time():- It takes date as input return a string.
%b Month Dec
%B Month December
%m Month in number 12
%y Year without century 23
%Y Year with century 2023
%H Hour (24 hr format) 16
%I Hour (12 hr format) 04
%p AM/PM Pm
%M Minute 41
%S Second 50

Import datetime
Now = datetime .datetime.now()
Year=now.strftime(“y.Y”)
Print(year)
O/P:- 2023

5). Math module:-


1. Ceil() :-
Import Math
X=10.5
Print(math ceil(x))
O/P:- 11
2. Floor() :-
Import math
X=10.5
Print(math.floor(x))
O/P:- 10
3. Sqrt():-
Math.sqrt(144)
O/P:-12
4. Pi ():-
Print(math.pi)
O/P:-3.14
5. Tabs:- It return absolute value
a= -10
math.tabs(a)
O/P:-10
6. Pow():-
Print(pow(3,2))
O/P:-9

Numpy:-
 Numpy stands for numeric python which is a python package for
the computation and processing of the multidimensional and single
dimensional array elements.
 Numpy provides a convenient and efficient way to handle the vast
amount of data Numpy is very convenient with matrix
multiplication and data reshaping.
 Numpy is fast which makes it reasonable to work with a large set
of data.
 Advantages of numpy in data Analysis.
1) Numpy performs array-oriented computing.
2) It efficiently implements the multi-dimensional arrays.
3) It perform scientific computations.
4) It is capable of performing fourier transform and reshaping
the data stored in multi-dimensional arrays.
5) Numpy provides the in-built functions for linear algebra and
random number generation.
 Numpy is a python library used for working with arrays.
 Numpy was created by Travis Oliphant in 2005. It is open source
project and you can use it freely.
 In python we have lists, that serve the purpose of arrays, but they
are slow to process.
 Numopy aims to provide an array object that is up to 50x faster
than traditional python lists.
 The array, object in numpy is called ndarray, it provides a lot of
supporting functions that make working with ndarray very easy.
 Arrays are very frequently used in data science, where speed and
resources are very important.
 [The elements in the list are not stored themselves Instead, every
element of the list in stored at random locations, and list stores the
address of those random locations]
 Numpy array are stored at one continuous place in memory unlike
lists, so processes can access and manipulate them very efficiently.
 Numpy is a python library and is written partially in python, but
most parts that require fast computation are written in C or C++.

Installation of Numpy:-
 If python & PIP already installed on a system then use the
command
 pip install numpy
Ex:-
Import numpy
A=numpy.array([21,41,50,60])
Print(A)
O/P:- [21,41,50,60]

Numpy as np:-
Numpy imported under np alias(alternate name)
Import humpy as np

Checking numpy version


 The version string is stored under ---version---- attribute
Import numpy as np
Print(np—version--)
O/P:-1.24.4

Numpy Creating Array:-


 Numpy is used to work with arrays. The array object in Numpy is
called ndarray.
 Ndarray object is created using array() function.
Import numpy as np
A=np.array([21,45,50,60])
Print(A)
Print(type(A))
O/P:- [21 45 50 60 ]
< class ‘numpy.ndarray’>
Type():- This built-in python function tells us the type of the object
passed to it.
List,
Tuple,
Array-likearray()ndarray

Import numpy as np
1. a= np.array(53)
print(0)
print(‘Dimension is’,a.ndim)
O/P:- 53
Dimension is 0
2)a= np.array([21,45,60,70])
Print(a)
Print(‘dimension is’,a.ndim)
O/P:- [21,45,60,70]
Dimension is 1
3)a=np.array([1,2,3],[4,5,6]);
Print(a)
Print(‘Dimension is’,a.ndim)
O/P:- [[1 2 3]
[4 5 6]]
Dimension is 2
4)a=np.array([[[7,8,9],[11,12,13]],[[21,22,23],[24,25,26]]]
Print(a)
Print(‘dimension is’,a.ndim)
O/P:- [[[7 8 9 ]
[11 12 13]]
[[21 22 23]
[24 25 26]]]
Dimension is 3

Higher Dimensional Arrays:


 an array can have any number of dimensions.
 When the array is created, you can define the number of
dimensions by using the ndin Argument.
Ex:- import numpy as np
b=np.array([21,40,50,61],ndim=6)
print(b)
print(‘number of dimensions:’,b.ndim)
O/P:- [[[[[[21 40 50 61]]]]]]
Number of dimensions : 6

Numpy Array Indexing:


 Access array elements in 1-D array
 Indexing in array starts with 0
Ex:- import numpy an np
a=np.array([21,45,60,70])
print(a[0])
O/P:- 21

Ex:- import numpy as np


a=np.array([20,30,10,11])
print(a[20]+a[3])
print(a[0]/a[2])
O/P:- 21
2.0

Access 2-D array:-


 2-D array is like a table with rows and columns.
Ex:- Access the element on the 2nd row, 5th column
b=np.array ([[1,2,3,4,5]
[21,22,23,24,25]])
Print(‘5th element of 2nd row;,a[1,4])
O/P:-25

Access 3-D array:-


 To access elements from 3-D arrays we use comma separated
integers representing the dimensions and the index of the elements.
Ex:- access the third elements of second array of the first array
Import numpy as np
A=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
Print(a[0,1,2])

2-D array:-
Ex:- from second array, slice elements from index 1 to index 4(not
includes)
Import numpy as np
a=np.array([[1,2,3,4,5],[6,7,8,9,10]])
print(a[1,1.4])
O/P:-[7 8 9]

Import numpy as np
A=np.array9[21,22,23,24,25,26,27])
Print(a[-3:-1])
O/P:-[25 26]

Step:-
Use of step value to determine the step of slicing.
Ex:- import numpy as np
a=np.array([1,2,3,4,5,6,7])
@print(a[1.5:2])
O/P:-[2 4]
B print(a[::2])
O/P:-[1 3 5 7]

Negative Indexing:-
Use negative indexing to access an array from the end.
Ex:- import numpy as np
a=np.array([11,12,13,14,15],[16,17,18,19,20])
print(‘last element from 2nd dimension’,a[1,-1])
O/P:-20

Slicing Array:-
 Slicing in python means taking elements from one given index to
another given index.
 We pass slice instead of index like i) [start : end]
 ii)[start : end : step]
 If we don`t pass start it considered 0
 If we don`t end it considered length of array in that dimension.
 If we don`t pass step it considered 1:
Ex:- slice element from index 1 to index 5 from following array
Import numpy as np
a=np.array([21,22,23,24,25,26,27])
print(A[1:5])
O/P:-[22 23 24 25]
 The result includes the start index but exclude the end index.

Negative slicing:-
 Ex:- slice from index 3 from end to index 1 from the end.
Datatypes in Numpy
1) Strings:- used to represent text data, the text is given under quote
marks E.g:- “Anaconda”
2) Integer:- it is used to represent integer numbers E.g:-100,101,1,2,-3
3) Float:- it is used to represent real numbers
E.g:- 1.2,42,42,63.31
4) Boolean:- it is used to represent true or false.
5)Complex:- it is used to represent complex numbers.
E.g:- 1.0+2.0 , 1.5+2.5;

Checking data type of an array:-


Import numpy as np
Arr=np.array([1,2,3,4])
Print(arr.dtype)
O/P:- int 64
Arr=np.array[(‘apple’,’banana’,’ cherry’)]
Print(arr.dtype)
O/P:-<U6
Creating Array with a defined data type
 We use array() function to create arrays, this function take the
arguments for dtype that allow to define the excepted data type of
the array elements.
Import numpy as np
Arr=np.array([1,2,3,4],dtype=’5’)
Print(arr)
Print(arr.dtype)
[‘1’ ‘2’ ‘3’ ‘4’]
For i,u,f,s,u we can define size as well
Import numpy as np
Arr=np.array([1,2,3,4],dtype=’14’)
Print(arr)
Print(arr.dtype)
O/P:- [1 2 3 4] int 32

Value Error :-
Import numpy as np
Arr=np.array([‘a’,’2’,’3’], dtype=’i’)
O/P:- value error

Import numpy as np
arr=np.array([1.1,2.1,3.1])
new arr=arr.astyle(‘i’)
print(newarr)
print(newarr.dtype)
O/P:-[1 2 3]
Int 32
astyle() function creates a copy of array allow you to specify the
datatypes as parameters.
Change datatype from float to integer using int as parameter value
Import numpy as np
Arr=np.array ([1.1,2.1,3.1])
Newarr=arr.astyle(int)
Print(newarr)
Print(newarr.dtype)
O/P:-[1 2 3]
Int 64
i integer
b Boolean
u Unsigned integer
f Float
c Complex float
m timedelta
M datetime
O Object
S String
U Unicode string
V Fixed chunck of memory for other
type(void).

Pandas:-
 Pandas is python library used for working with data sets.
 It has functions for analyzing, cleaning, exploring and
manipulating data.
 The name “pandas” has a reference to both “panal data” and
“python data Analysis” and created by Wes Mckinney in 2008.
 Pandas allow us to analyze big data and make conclusions based
on statistical theories.
 Pandas can clean messy data sets and make them readable and
relevant.
 Installation on pandas
Installation it using following command
 Pip install pandas
Import pandas as pd
Mydata set={ ‘name’:[“ram”,”sita”,”hari”],’marks’:[10,12,13] }
Data=pd.Dataframe(mydataset)
Print(data)
O/P:-
Names Marks
0 Ram 10
1 Sita 12
2 Hari 13

Checking pandas version:


Import pandas as pd
Print(pd---version---)
O/P:-1.0.3

Series:
 A pandas series is like a column in table.
 It is one-dimensional array holding data of any type.
 Ex:-create a simple pandas series from a list
Import pandas as pd
A=[1,2,3,4]
Sample=pd.series(a)
Print(sample)
O/P:-
0 1
1 2
2 3
3 4
Dtype: int 64

Labels:
 If nothing else is specified , the values are labeled with their index
number. First value has index 0, second value has index 1 etc.
 This label can be used to access a specified value.
 Ex:-return the third value of the series.
Import pandas as pd
A=[1,2,3,4]
Sample=pd.series(a)
Print(sample[2])
O/P:-3

Create label:
 With the index argument , you can name your own labels.
 Ex:- create your own labels
Import pandas as pd
A=[1,2,3,4,5]
Sample=pd.series(a,index=”p”,”q”,”r”,”s”,”t”)
Print(sample)
O/P:-
p 1
q 2
r 3
s 4
t 5
Dtype=int 64
 When you create labels ,you can access an item by referring to the
label.
Print(sample[“t”])
O/P:-5

Data frame:
 A pandas dataframe is 2 dimensional data structure like 2-D Array
or table with rows and columns.
 Ex:- create a simple pandas dataframe
Import pandas as pd
Sample data={ “calories” [420,380,390], “durations” [50,40,45] }
# load data into a dataframe object:-
df= pd.Dataframe(data)
print(df)
O/P:-
Calories Durations
0 420 50
1 380 40
2 390 45

Named Indexed:
 With the index argument, you can name your own indexes.
 Ex:- Add a list of names to give each row of a name.
Import pandas as pd
Sampledata={ “calories” [420,380,390], “duration” [50,40,45] }
df= pd.dataframe (sampledata, index=[“day1”,”day2”,”day3”])
print(df)
O/P:-
Calories Durations
Day1 420 50
Day2 380 40
Day3 390 45

Locate Row:
 Pandas use the loc attribute to return one or more specified rows(s)
 Ex:- return row 0
# refer to the index :
Print(df.loc[0])
O/P:-
Calories 420
Duration 50
Name: dtype: int 64
Ex: Return row 0 and 1
# use a list of indexes:
Print(df.loc[[0,1]])
O/P:-
Calories Durations
0 420 50
1 380 40
Located Named Indexes:
 Use the named index in the loc attribute to return the specified
row(s)
 Ex:- Return “day 2”
# refer to the named index:
Print(df.loc[“day2”])
O/P:-calories – 380
Durations- 40
Name: day2 dtype: int 64

Load files into a Dataframe


 If your data set are stored in a file, pandas can load them into a
dataframe.
 Ex:- load a comma separated file
(CSV file) into a Data frame
Import pandas as pd
df=pd.read_CSV(‘cardiogood fitness’)
print(df)
O/P:- It only return first S rows & last 5 rows

To_string() :- to print entire dataframe.


 import pandas as pd
df=pd.read_CSV('cardiogood fitness’)
print(df. To_string)
O/P:-All data

Max_rows:
 the numbers of rows returned is defined in pandas option setting
 you can check your systems maximum rows with the
pd.options. display.max_rows statement
import pandas as pd
print(pd.options.display.max_rows)
O/P:-60 OR 80

You might also like