Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
210 views

python-notes-BCC-302 (Unit - 05)

best notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
210 views

python-notes-BCC-302 (Unit - 05)

best notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

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. It is
open-source software.

Features of NumPy

NumPy has various features including these important ones:

 A powerful N-dimensional array object

 Sophisticated (broadcasting) functions

 Tools for integrating C/C++ and Fortran code

 Useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy in Python can also be used as an
efficient multi-dimensional container of generic data. Arbitrary data types can be
defined using Numpy which allows NumPy to seamlessly and speedily integrate
with a wide variety of databases.

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.

NumPy Array Creation

There are various ways of Numpy array creation in Python. They are as follows:
1. You can create an array from a regular Python list or tuple using the array()
function. The type of the resulting array is deduced from the type of the elements
in the sequences. Let’s see this implementation:

import numpy as np

# Creating array from list with type float

a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')

print ("Array created using passed list:\n", a)

# Creating array from tuple

b = np.array((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. Often, the element is of an array is originally unknown, but its size is known.
Hence, NumPy offers several functions to create arrays with initial placeholder
content. These minimize the necessity of growing arrays, an expensive
operation. For example: np.zeros, np.ones, np.full, np.empty, etc.

To create sequences of numbers, NumPy provides a function analogous to the


range that returns arrays instead of lists.

# Creating a 3X4 array with all zeros

c = np.zeros((3, 4))
print ("An array initialized with all zeros:\n", c)

# Create a constant value array of complex type

d = np.full((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 = np.random.random((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 6s.Array 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. arange: 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 = np.arange(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. linspace: It returns evenly spaced values within a given interval.

# Create a sequence of 10 values in range 0 to 5

g = np.linspace(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. Reshaping array: We can use reshape method to reshape an array. Consider an


array with shape (a1, a2, a3, ….. , aN). We can reshape and convert it into another
array with shape (b1, b2, b3, …... , bM). The only required condition is a1 x a2 x
a3 &#x2026 x aN = b1 x b2 x b3 …… x bM. (i.e. the original size of the array
remains unchanged.)

# Reshaping 3X4 array to 2X2X3 array

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

[5, 2, 4, 2],

[1, 2, 0, 1]])

newarr = arr.reshape(2, 2, 3)

print ("Original array:\n", arr)

print("---------------")

print ("Reshaped array:\n", newarr)

Output:

Original array:

[[1 2 3 4]

[5 2 4 2]

[1 2 0 1]]

---------------
Reshaped array:

[[[1 2 3]

[4 5 2]]

[[4 2 1]

[2 0 1]]]
NumPy Array Indexing

Knowing the basics of NumPy array indexing is important for analyzing and
manipulating the array object. NumPy in Python offers many ways to do array
indexing.

 Slicing: 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.

 Integer array indexing: In this method, lists are passed for indexing for
each dimension. One-to-one mapping of corresponding elements is done to
construct a new arbitrary array.

 Boolean array indexing: This method is used when we want to pick


elements from the array which satisfy some condition.

# Python program to demonstrate

# indexing in numpy

import numpy as np

# An exemplar array

arr = np.array([[-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)

Output:

Array with first 2 rows and alternatecolumns(0 and 2):

[[-1. 0.]

[ 4. 6.]]

Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):

[ 4. 6. 0. 3.]

Elements greater than 0:

[ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]

NumPy Basic Operations

The Plethora of built-in arithmetic functions is provided in Python NumPy.


Operations on a single NumPy array

We can use overloaded arithmetic operators to do element-wise operations on the


array to create a new array. In the case of +=, -=, *= operators, the existing array is
modified.

# Python program to demonstrate

# basic operations on single array

import numpy as np

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

# add 1 to every element

print ("Adding 1 to every element:", a+1)

# subtract 3 from each element

print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10

print ("Multiplying each element by 10:", a*10)

# square each element

print ("Squaring each element:", a**2)

# modify existing array

a *= 2

print ("Doubled each element of original array:", a)

# transpose of array

a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

print ("\nOriginal array:\n", a)


print ("Transpose of array:\n", a.T)

Output:

Adding 1 to every element: [2 3 6 4]

Subtracting 3 from each element: [-2 -1 2 0]

Multiplying each element by 10: [10 20 50 30]

Squaring each element: [ 1 4 25 9]

Doubled each element of original array: [ 2 4 10 6]

Original array:

[[1 2 3]

[3 4 5]

[9 6 0]]

Transpose of array:

[[1 3 9]

[2 4 6]

[3 5 0]]

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. In the case of +=, -=, =
operators, the existing array is modified.

# Python program to demonstrate

# binary operators in Numpy

import numpy as np
a = np.array([[1, 2],

[3, 4]])

b = np.array([[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", a.dot(b))

Output:

Array sum:

[[5 5]

[5 5]]

Array multiplication:

[[4 6]

[6 4]]

Matrix multiplication:

[[ 8 5]

[20 13]]
PANDAS

Pandas is a powerful and versatile library that simplifies tasks of data manipulation
in Python. Pandas is built on top of the NumPy library and is particularly well-
suited for working with tabular data, such as spreadsheets or SQL tables. Its
versatility and ease of use make it an essential tool for data analysts, scientists, and
engineers working with structured data in Python.

Installing Pandas

The first step of working in pandas is to ensure whether it is installed in the system
or not. If not then we need to install it in our system using the pip command.
Type the cmd command in the search box and locate the folder using the cd
command where python-pip file has been installed. After locating it, type the
command:

pip install pandas

Importing Pandas

After the pandas have been installed into the system, you need to import the
library. This module is generally imported as follows:

import pandas as pd

Here, pd is referred to as an alias to the Pandas. However, it is not necessary to


import the library using the alias, it just helps in writing less amount code every
time a method or property is called.

Pandas Data Structures

Pandas generally provide two data structures for manipulating data, They are:

 Series

 DataFrame
SERIES

A Pandas Series is a one-dimensional array-like object that can store data of any
type, including strings, integers, and floats. It has an associated index, which is an
array of labels used to identify elements within the Series. Series can only contain
a single list with index labels, but they are easy to construct and manipulate.

Creating a simple pandas series from a list:


import pandas as pd
a = [1,2,3]
ds = pd.Series(a)
print(ds)

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.

print(ds[0])

With the index argument, you can name your own labels.

import pandas as pd
a = [1,2,3]
ds = pd.Series(a, index=[‘a’, ‘b’, ‘c’])
print(ds)

When you have created labels, you can access an item by referring to the label.

print(ds[“a”])

A series can also be created by using key/value object, like dictionary.


import pandas as pd
AQI = {"day1": 420, "day2": 380, "day3": 390}
ds = pd.Series(AQI)
print(ds)

DATAFRAMES

A Pandas DataFrame is a two-dimensional data structure that contains columns and


rows of data. It is similar to a spreadsheet, with each row representing an
observation and each column representing a variable. DataFrames can contain
multiple data types, including strings, integers, and floats. They are more complex
to construct but offer a far greater range of capabilities and are ideal for working
with larger datasets.

import pandas as pd
data = {"AQI": [420, 380, 390], "Temp": [50, 40, 45]}
df = pd.DataFrame(data)
print(df)

The DataFrame is like a table with rows and columns. Pandas use the loc attribute
to return one or more specified row(s).

print(df.loc[0])

To return row 0 and 1:

print(df.loc[[0,1,2]])

In DataFrame, index argument can


be used to name your own indexes.

import pandas as pd
data = {"AQI": [420, 380, 390], "Temp": [50, 40, 45]}
df = pd.DataFrame(data, index=[“day1”, “day2”, “day3”])
print(df)

To load a comma separated file (CSV file) into a DataFrame:


Download file from https://www.w3schools.com/python/pandas/data.csv
import pandas as pd
df = pd.read_csv('data.csv')
print(df)

to_string() to print the entire DataFrame.

print(df.to_string())
To load JSON file into a DataFrame:

JSON objects have the same format as Python dictionaries.

Download file from https://www.w3schools.com/python/pandas/data.js

import pandas as pd
df = pd.read_json('data.json')
print(df.to_string())

To get a quick overview of the DataFrame:


import pandas as pd
df = pd.read_json(‘data.json’)
print(df.head())

head()method is used to return top n (5 by default) rows of a data frame or series.

print(df.head(10))

df.head(10) returns the top 10 rows of the DataFrame.

Pandas tail()method is used to return bottom n (5 by default) rows of a data frame


or series.

print(df.tail())
df.tail() returns the bottom 5 rows of the DataFrame.

Pandas uses the mean() median() and mode() methods to calculate the respective
values for a specified column:

import pandas as pd
df = pd.read_csv('data.csv')
x = df["Calories"].mean()
print(x)

Adding new row to the DataFrame:


import pandas as pd
df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age':
[25, 30, 35]})
new_row = {'Name': 'David', 'Age': 40}
df.loc[len(df)] = new_row
df = df.reset_index(drop=True)
print(df)
The reset_index() method allows you to reset the index back to the default 0, 1, 2
etc indexes.
By default this method will keep the "old" indexes in a column named "index", to
avoid this, use the drop parameter.
Deleting a column from
DataFrame:
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob',
'Charlie'], 'Age': [25, 30,
35]})
df = df.drop('Age',axis=1)
print(df)

MATPLOTLIB AND ITS BUILT IN FUNCTIONS

Matplotlib is a Python library that enables users to generate visualizations like


histograms, scatter plots, bar charts, pie charts and much more. It is built on
NumPy arrays and is often used in conjunction with the pandas library for data
analysis. Matplotlib is a powerful tool for creating visualizations, and it offers a
wide range of features and customization options.

Matplotlib is a popular choice for data visualization in Python, and it is used by a


wide range of users, including scientists, engineers, and data analysts. It is a
powerful and versatile tool that can be used to create a variety of visualizations,
from simple to complex.

Pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:

from matplotlib import pyplot as plt


Plotting x and y points on a graph:

from matplotlib import pyplot as plt


import numpy as np
xpoints = np.array([1,2, 4, 8])
ypoints = np.array([3,7,5, 10])
plt.plot(xpoints, ypoints)
plt.show()

The plot() function is used to draw points


(markers) in a diagram. By default, the
plot() function draws a line from point to
point.

Using default x points on the graph:

from matplotlib import pyplot as plt


import numpy as np
ypoints = np.array([3,7,5, 10])
plt.plot(ypoints)
plt.show()

The x-points in the example above are [0,


1, 2, 3]

plt.show() starts an event loop, looks for all currently active figure objects, and
opens one or more interactive windows that display your figure or figures.
plt.show() command should be used only once per Python session, and is most
often seen at the very end of the script. Multiple show() commands can lead to
unpredictable backend-dependent behavior, and should mostly be avoided.
Creating title and labels:

import numpy as np
from matplotlib import pyplot as plt
x = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
y = np.array([8, 5, 9, 5, 10, 15, 11, 16, 12, 25])
plt.plot(x, y)
plt.title("Warehouse")
plt.xlabel("Date")
plt.ylabel("Quantity")
plt.show()

title, xlabel and ylabel are added to the plot using the title(), xlabel(), and ylabel()
functions of the matplotlib library.

CREATING DIFFERENT TYPES OF GRAPH

1. Line graph
from matplotlib import pyplot as plt
x = [16, 8, 10]
y = [8, 16, 6]
x2 = [8, 15, 11]
y2 = [6, 15, 7]
plt.plot(x, y, 'r')
plt.plot(x2, y2, 'm')
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
2. Bar graphs
Bar graphs are one of the most common types of graphs and are used to show data
associated with the categorical variables. Matplotlib provides a bar() to make bar
graphs which accepts arguments such as: categorical variables, their value and
color.

from matplotlib import pyplot as plt


Students = ['XY','AB','PQ','RS']
Marks = [31,17,40,26]
plt.bar(Students,Marks,color = 'blue')
plt.title('Score Card')
plt.xlabel('Students')
plt.ylabel('Marks')
plt.show()

Another function barh() is used to make


horizontal bar graphs.

3. Pie Chart
A pie chart is a circular graph that is broken down in the segment or slices of pie. It
is generally used to represent the percentage or proportional data where each slice
of pie represents a particular category. The pie() function to draw pie charts.

from matplotlib import pyplot as plt


import numpy as np
y = np.array([35, 25, 25, 15])
plt.pie(y)
plt.show()

The size of each wedge is determined by comparing


the value with all the other values, by using this
formula:
The value divided by the sum of all values: x/sum(x)
from matplotlib import pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["XY", "AB", "PQ", "RS"]
plt.pie(y, labels = mylabels)
plt.legend()
plt.show()

4. Histogram
First, we need to understand the difference
between the bar graph and histogram.
A histogram is used for the distribution, whereas a bar chart is used to compare
different entities. A histogram is a type of bar plot that shows the frequency of a
number of values compared to a set of values ranges. The hist() function to create
histograms. The hist() function will use an array of numbers to create a histogram,
the array is sent into the function as an argument.

from matplotlib import pyplot as plt


population_age=
[21,53,60,49,25,27,30,42,40,1,2,102,95,8,15,105,
70,65,55,70,75,60,52,44,43,42,45]
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age, bins, histtype='bar')
plt.xlabel('age groups')
plt.ylabel('Number of people')
plt.title('Histogram')
plt.show()

5. Scatter plot
The scatter plots are mostly used for comparing variables when we need to define
how much one variable is affected by another variable. The data is displayed as a
collection of points. Each point has the value of one variable, which defines the
position on the horizontal axes, and the value of other variable represents the
position on the vertical axis.
from matplotlib import pyplot as plt
x = [5,7,10]
y = [18,10,6]
x2 = [6,9,11]
y2 = [7,14,17]
plt.scatter(x, y)
plt.scatter(x2, y2)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

from matplotlib import pyplot as plt


x = [2, 2.5, 3, 3.5, 4.5, 4.7, 5.0]
y = [7.5, 8, 8.5, 9, 9.5, 10, 10.5]
x1 = [9, 8.5, 9, 9.5, 10, 10.5, 12]
y1 = [3, 3.5, 4.7, 4, 4.5, 5, 5.2]
plt.scatter(x, y, label='high income low saving',
color='green')
plt.scatter(x1, y1, label='low income high
savings', color='red')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()
PYTHON GUI - TKINTER
Python offers multiple options for developing GUI (Graphical User Interface). Out
of all the GUI methods, tkinter is the most commonly used method. It is a standard
Python interface to the Tk GUI toolkit shipped with Python. Python tkinter is the
fastest and easiest way to create GUI applications. Creating a GUI using tkinter is
an easy task.

1. Importing the module – tkinter


2. Create the main window (container)
3. Add widgets to the main window

Importing a tkinter is the same as importing any other module in the Python code.
import tkinter
Two main methods used which the user needs to remember while creating the
Python application with GUI.

Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create


a main window, tkinter offers a method ‘Tk(screenName=None,
baseName=None, className=’Tk’, useTk=1)’. To change the name of the
window, you can change the className to the desired one. The basic code used to
create the main window of the application is:

m=tkinter.Tk() #where m is the name of the main window object

mainloop(): There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the
application, wait for an event to occur and process the event as long as the window
is not closed.
m.mainloop()

Tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainly three geometry
manager classes class.
1. pack() method:It organizes the widgets in blocks before placing in the parent
widget.
2. grid() method:It organizes the widgets in grid (table-like structure) before
placing in the parent widget.
3. place() method:It organizes the widgets by placing them on specific
positions directed by the programmer.

Some of the common widgets used in Tkinter are :

o Text : It enables us to display and alter text in a variety of styles and offers a
prepared text display.
o Label : Used to display text and images, but we are unable to interact with it.
o Button : Often used add buttons and we may add functions and methods to
it.
o Entry : One-line string text can be entered into this widget.
o Radiobutton : Use a radio button to carry out one of several choices.

from tkinter import*


base = Tk()
base.geometry('500x500')
base.title("Registration Form")

labl_0 = Label(base, text="Registration form",width=20,font=("bold", 20))


labl_0.place(x=90,y=53)

labl_1 = Label(base, text="FullName",width=20,font=("bold", 10))


labl_1.place(x=80,y=130)

entry_1 = Entry(base)
entry_1.place(x=240,y=130)
labl_2 = Label(base, text="Email",width=20,font=("bold", 10))
labl_2.place(x=68,y=180)

entry_02 = Entry(base)
entry_02.place(x=240,y=180)

labl_3 = Label(base, text="Gender",width=20,font=("bold", 10))


labl_3.place(x=70,y=230)
varblbl = IntVar()
Radiobutton(base, text="Male",padx = 5, variable=varblbl,
value=1).place(x=235,y=230)
Radiobutton(base, text="Female",padx = 20, variable=varblbl,
value=2).place(x=290,y=230)

labl_4 = Label(base, text="Age:",width=20,font=("bold", 10))


labl_4.place(x=70,y=280)

entry_02 = Entry(base)
entry_02.place(x=240,y=280)

Button(base, text='Submit',width=20,bg='brown',fg='white').place(x=180,y=380)

base.mainloop()

You might also like