0% found this document useful (0 votes)
30 views19 pages

PPS Lab Manual 11-14

Uploaded by

joshuvaamalan15
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)
30 views19 pages

PPS Lab Manual 11-14

Uploaded by

joshuvaamalan15
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/ 19

Ex No: 11

Date: PYTHON DATA STRUCTURES

The data structures are the organizers and storers of data in an efficient manner so that
they can be modified and accessed in the future. To suit different uses, there are different
data structures in Python. These can be mainly classified into two types:

1. Python Built-in data structures:


These are the data structures that come along with Python and can be
implemented same as primitive data types like integers, etc. These can be further
classified into:
• Lists
• Sets
• Tuples
• Dictionaries

2. Python User-defined data structures:


These data structures are the ones built using the built-in data structures and
have their own properties. Based on these features, these are used in suitable
situations. These can be subdivided into:

• Stack
• Queue
• Linked List
• Hash maps
• Trees
• Graphs
LISTS

Aim
To write a Python program to create a list.

Algorithm
Step 1: Initialize a List
Step 2: Print the List with Multiple Values
Step 3: Initialize a Multi-Dimensional List
Step 4: Print the Multi-Dimensional List
Step 5: Access Elements from the List
Step 6: Access the First and Third Elements Using Positive Indexing
Step 7: Access Elements Using Negative Indexing
Step 8: Access the Last and First Elements Using Negative Indexing

Program
List = ["She", "Loves", "Cricket"]
print("\nList containing multiple values: ")
print(List)
List2 = [['She', 'Loves'], ['Cricket']]
print("\nMulti-Dimensional List: ")
print(List2)
print("Accessing element from the list")
print(List[0])
print(List[2])
print("Accessing element using negative indexing")
print(List[-1])
print(List[-3])

Output
List containing multiple values:
['She', 'Loves', 'Cricket']
Multi-Dimensional List:
[['She', 'Loves'], ['Cricket']]
Accessing element from the list
She
Cricket
Accessing element using negative indexing
She
Cricket
DICTIONARY

Aim
To write a Python program to create a dictionary.

Algorithm
Step 1: Initialize a Dictionary
Step 2: Create a dictionary named Dict with two key-value pairs:
Step 3: Print the Dictionary
Step 4: Display a message indicating the creation of the dictionary.

Program
Dict = {'Name': 'Velan', 1: [1, 2, 3, 4]}
print("Creating Dictionary: ")
print(Dict)
print("Accessing a element using key:")
print(Dict['Name'])
print("Accessing a element using get:")
print(Dict.get(1))
myDict = {x: x**2 for x in [1,2,3,4,5]}
print(myDict)

Output
Creating Dictionary:
{'Name': 'Velan', 1: [1, 2, 3, 4]}
Accessing a element using key:
Geeks
Accessing a element using get:
[1, 2, 3, 4]
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
TUPLES

Aim
To write a Python program to create a tuple.

Algorithm
Step 1: Initialize a Tuple with Strings
Step 2: Print the Tuple
Step 3: Initialize a List
Step 4: Convert the List to a Tuple
Step 5: Print the Tuple Created from the List
Step 6: Access the First Element of the Tuple
Step 7: Access the Last Element of the Tuple Using Negative Indexing
Step 8: Access the Third Last Element of the Tuple Using Negative Indexing

Program
Tuple = ('Velan', 'She')
print("\nTuple with the use of String: ")
print(Tuple)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
Tuple = tuple(list1)
print("First element of tuple")
print(Tuple[0])
print("\nLast element of tuple")
print(Tuple[-1])
print("\nThird last element of tuple")
print(Tuple[-3])

Output
Tuple with the use of String:
('Velan', 'She')
Tuple using List:
First element of tuple
1
Last element of tuple
6
Third last element of tuple
4
SETS

Aim
To write a Python program to create a set.

Algorithm
Step 1: Initialize a Set with Mixed Values
Step 2: Print the Set
Step 3: Iterate Over the Set Elements
Step 4: Display a message indicating the elements of the set will be printed.
Step 5: Use a for loop to iterate over each element in the set and print it.
for i in Set:
print(i, end=" ")
Step 6: Print a Blank Line
Step 7: Check for the Presence of an Element in the Set
Step 8: Print the element in Set.

Program
Set = set([1, 2, 'Velan', 4, 'Loves', 6, 'Singing'])
print("\nSet with the use of Mixed Values")
print(Set)
print("\nElements of set: ")
for i in Set:
print(i, end =" ")
print()
print("Geeks" in Set)

Output

Set with the use of Mixed Values


{1, 2, 'Velan', 4, 6, 'Loves'}

Elements of set:
1 2 Velan 4 6 Loves
True
Ex No: 12

Date: ARRAYS IN PYTHON

The Array is an idea of storing multiple items of the same type together, making it easier
to calculate the position of each element by simply adding an offset to the base value.
A combination of the arrays could save a lot of time by reducing the overall size of the
code. It is used to store multiple values in a single variable. If you have a list of items
that are stored in their corresponding variables like this:

car1 = "Lamborghini"
car2 = "Bugatti"
car3 = "Koenigsegg"

If you want to loop through cars and find a specific one, you can use the Array. You can
use an array to store more than one item in a specific variable.
The Array can be handled in Python by a module named Array. It is useful when we
must manipulate only specific data values. The following are the terms to understand
the concept of an array:

Element - Each item stored in an array is called an element.


Index - The location of an element in an array has a numerical index, which is used to
identify the element's position. The index value is very much important in an Array.

Array operations
1. Traverse - It prints all the elements one by one.
2. Insertion - It adds an element at the given index.
3. Deletion - It deletes an element at the given index.
4. Search - It searches an element using the given index or by the value.
5. Update - It updates an element at the given index.

The Array can be created in Python by importing the array module to the python
program.

from array import *


arrayName = array(typecode, [initializers])
ACCESS THE ELEMENT

Aim
To write a Python program to access the element in an array.

Algorithm
Step 1: Import the Array Module
Step 2: Initialize an Array of Integers
Step 3: Access and Print Elements Using Positive Indexing
Step 4: Access and Print Elements Using Negative Indexing
Step 5: Print All Elements Together

Program
import array as arr
a = arr.array('i', [2, 4, 5, 6])
print("First element is:", a[0])
print("Second element is:", a[1])
print("Third element is:", a[2])
print("Forth element is:", a[3])
print("last element is:", a[-1])
print("Second last element is:", a[-2])
print("Third last element is:", a[-3])
print("Forth last element is:", a[-4])
print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])

Output:
First element is: 2
Second element is: 4
Third element is: 5
Forth element is: 6
last element is: 6
Second last element is: 5
Third last element is: 4
Forth last element is: 2
24566542
ADDING ARRAY ELEMENTS

Aim
To write a Python Program to add or change or replace an element in an array.

Algorithm
Step 1: Import the Array Module
Step 2: Initialize an Array of Integers
Step 3: Modify the First Element of the Array
Step 4: Print the Array After Modifying the First Element
Step 5: Modify the Last Element of the Array
Step 6: Print the Array After Modifying the Last Element
Step 7: Modify a Range of Elements in the Array
Step 8: Print the Array After Modifying the Range of Elements

Program
import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
numbers[0] = 0 # changing first element 1 by the value 0.
print(numbers)
numbers[5] = 8 # changing last element 10 by the value 8.
print(numbers)
numbers[2:5] = arr.array('i', [4, 6, 8]) # replace the value of 3rd to 5th element by 4, 6 and 8
print(numbers)

Output
array('i', [0, 2, 3, 5, 7, 10])
array('i', [0, 2, 3, 5, 7, 8])
array('i', [0, 2, 4, 6, 8, 8])
ARRAY CONCATENATION

Aim
To write a Python program to concatenate the elements in an array.

Algorithm
Step 1: Import the Array Module
Step 2: Initialize Array a with Floating-Point Numbers
Step 3: Initialize Array b with Floating-Point Numbers
Step 4: Initialize an Empty Array c
Step 5: Concatenate Arrays a and b
Step 6: Print the Resulting Array c

Program
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])
b=arr.array('d',[3.7,8.6])
c=arr.array('d')
c=a+b
print("Array c = ",c)

Output
Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
Ex No: 13

Date: OPERATIONS WITH NumPy

NumPy is a powerful Python library that can manage different types of data. Here we will
explore the Datatypes in NumPy and How we can check and create datatypes of the NumPy
array.

Datatypes in NumPy
A data type in NumPy is used to specify the type of data stored in a variable. Here is the list
of characters to represent data types available in NumPy.

Character Meaning

b Boolean

f Float

m Time Delta

O Object

U Unicode String

i Integer

u Unsigned Integer

c Complex Float

M DateTime

S String

A fixed chunk of memory


V
for other types (void)
The list of various types of data types provided by NumPy are given below:
Data Type Description

bool_ Boolean

int_ Default integer type (int64 or int32)

intc Identical to the integer in C (int32 or int64)

intp Integer value used for indexing

int8 8-bit integer value (-128 to 127)

int16 16-bit integer value (-32768 to 32767)

int32 32-bit integer value (-2147483648 to 2147483647)

int64 64-bit integer value (-9223372036854775808 to 9223372036854775807)

uint8 Unsigned 8-bit integer value (0 to 255)

uint16 Unsigned 16-bit integer value (0 to 65535)

uint32 Unsigned 32-bit integer value (0 to 4294967295)

uint64 Unsigned 64-bit integer value (0 to 18446744073709551615)

float_ Float values

float16 Half precision float values

float32 Single-precision float values

float64 Double-precision float values

complex_ Complex values

complex64 Represent two 32-bit float complex values (real and imaginary)

complex128 Represent two 64-bit float complex values (real and imaginary)
CHECKING THE DATA TYPE OF NUMPY ARRAY

Aim
To write the Python Program to check the datatype of NumPy array.

Algorithm
Step 1: Import the NumPy Module
Step 2: Initialize a NumPy Array
Step 3: Determine the Data Type of the Array
Step 4: Print the Data Type

Program

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
data_type = arr.dtype
print("Data type:", data_type)

Output
Data type: int64
CREATE ARRAYS WITH A DEFINED DATA TYPE

Aim
To write a Python program to create an array with a defined data types in numpy.

Algorithm
Step 1: Import the NumPy Module
Step 2: Create Array arr1
Step 3: Create Array arr2
Step 4: Create Array arr3
Step 5: Create Array arr4
Step 6: Print Array arr1 and Its Data Type
Step 7: Print Array arr2 and Its Data Type
Step 8: Print Array arr3 and Its Data Type
Step 9: Print Array arr4 and Its Data Type

Program

import numpy as np
arr1 = np.array([1, 2, 3, 4], dtype=np.float64)
arr2 = np.zeros((3, 3), dtype=np.int32)
arr3 = np.ones((2, 2), dtype=np.complex128)
arr4 = np.empty((4,), dtype=np.bool_)
print("arr1:\n", arr1)
print("Data type of arr1:", arr1.dtype)
print("\narr2:\n", arr2)
print("Data type of arr2:", arr2.dtype)
print("\narr3:\n", arr3)
print("Data type of arr3:", arr3.dtype)
print("\narr4:\n", arr4)
print("Data type of arr4:", arr4.dtype)

Output
CONVERT DATA TYPE OF NUMPY ARRAYS

Aim
To write a Python program to convert data type of an array from one type to another.

Algorithm
Step 1: Import the NumPy Module
Step 2: Create the Original Array
Step 3: Convert the data type of arr_original to int32 using the astype() method and assign the
result to a new array named arr_new.
Step 4: Print the Original Array and Its Data Type
Step 5: Print the new array arr_new and its data type after conversion.

Program

import numpy as np
arr_original = np.array([1.2, 2.5, 3.7])
arr_new = arr_original.astype(np.int32)
print("Original array:", arr_original)
print("Data type of original array:", arr_original.dtype)
print("\nNew array:", arr_new)
print("Data type of new array:", arr_new.dtype)

Output
Ex No: 14

Date: OPERATIONS WITH PANDAS

Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data


structure with labeled axes (rows and columns). A Data frame is a two-dimensional data
structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame
consists of three principal components, the data, rows, and columns.
CREATING A PANDAS DATAFRAME

Aim
To write a Python program to create a panda dataframe.

Algorithm
Step 1: Import the Pandas Module
Step 2: Initialize a List
Step 3: Create a DataFrame from the List
Step 4: Print the DataFrame

Program
import pandas as pd
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
df = pd.DataFrame(lst)
print(df)

Output
DEALING WITH ROWS AND COLUMNS

Aim
To write a Python Program in order to select rows and columns in Pandas dataframe.

Algorithm
Step 1: Import the Pandas Module
Step 2: Create a dictionary named data with the following key-value pairs:
o 'Name': List of names ['Jai', 'Princi', 'Gaurav', 'Anuj']
o 'Age': List of ages [27, 24, 22, 32]
o 'Address': List of addresses ['Delhi', 'Kanpur', 'Allahabad', 'Kannauj']
o 'Qualification': List of qualifications ['Msc', 'MA', 'MCA', 'Phd']
Step 3: Create a DataFrame df from the dictionary data using the pd.DataFrame() constructor.
Step 4: Select and Print Specific Columns

Program
import pandas as pd
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
df = pd.DataFrame(data)
print(df[['Name', 'Qualification']])

Output
INDEXING A DATA

Aim
To write a Python program to index a data using Pandas.

Algorithm
Step 1: Import the Pandas Module
Step 2: Read a CSV file named "nba.csv" into a DataFrame named data. Use the "Name"
column as the index for the DataFrame.
Step 3: Select the "Age" Column
Step 4: Print the "Age" Column

Program
import pandas as pd
data = pd.read_csv("nba.csv", index_col ="Name")
first = data["Age"]
print(first)

Output
ITERATING OVER ROWS

Aim
To write a Python program to iterate over rows.

Algorithm
Step 1: Import the Pandas Module
Step 2: Create a Dictionary named dict with the following key-value pairs:
o 'name': List of names ["aparna", "pankaj", "sudhir", "Geeku"]
o 'degree': List of degrees ["MBA", "BCA", "M.Tech", "MBA"]
o 'score': List of scores [90, 40, 80, 98]
Step 3: Create a DataFrame from the Dictionary
Step 4: Iterate Over DataFrame Rows
for i, j in df.iterrows():
i: Index of the row.
j: Series object representing the row data.
Step 5: Print the Row Index and Data

Program
import pandas as pd
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
'degree': ["MBA", "BCA", "M.Tech", "MBA"],
'score':[90, 40, 80, 98]}
df = pd.DataFrame(dict)
for i, j in df.iterrows():
print(i, j)
print()

Output

You might also like