0% found this document useful (0 votes)
19 views35 pages

Lab 1 4 (AI) 1

The document outlines the objectives and content of a lab focused on the fundamentals of Artificial Intelligence and Python programming. It covers topics such as variable management, data types, loops, and conditional statements, providing examples and explanations for each concept. Additionally, it includes tasks for students to reinforce their understanding of Python programming principles.

Uploaded by

303-2023
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)
19 views35 pages

Lab 1 4 (AI) 1

The document outlines the objectives and content of a lab focused on the fundamentals of Artificial Intelligence and Python programming. It covers topics such as variable management, data types, loops, and conditional statements, providing examples and explanations for each concept. Additionally, it includes tasks for students to reinforce their understanding of Python programming principles.

Uploaded by

303-2023
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/ 35

Faculty of Computing and Information Technology

(FCIT) Department of Computing Indus University,


Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023

Lab no 1
Fundamentals of Artificial
Intelligence
Objectives:
Fundamental of Artificial Intelligence
 Introduction to Artificial Intelligence
 Types of Artificial Intelligence
 Machine learning vs. Deep learning vs. Artificial intelligence
Python for Artificial Intelligence
 Features and importance of Python for Artificial Intelligence
 Installation of Python
 Discus platform for python programming (Google Colab , Jupiter Notebook)

Python is a popular programming language. It was created by Guido van


Rossum, and released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 System scripting.

Python Syntax compared to other programming


languages
 Python was designed for readability, and has some similarities to
the English language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or
parentheses.
 Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming
languages often use curly-brackets for this purpose.

Variable in Python
 When you develop a program, you need to manage values, a lot of them.
To store values, you use variables.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
 In Python, a variable is a label that you can assign a value to it. And a
variable is always associated with a value. For example:

Naming variables
When you name a variable, you need to adhere to some rules. If you don’t,
you’ll get an error.

The following are the variable rules that you should keep in mind:

 Variable names can contain only letters, numbers, and underscores (_).
They can start with a letter or an underscore (_), not with a number.
 Variable names cannot contain spaces. To separate words in
variables, you use underscores for example sorted_list.

Datatypes
Python string
A string is a series of characters. In Python, anything inside quotes is a string.
And you can use either single quotes or double quotes. For example:

Creating multiline strings

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’. For
example:

Length of a string
To get the length of a string, you use the len() function. For example:

Slicing strings
Slicing allows you to get a substring from a string. For example:

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Number
Python supports integers, floats, and complex numbers.

Int
The integers are numbers such as -1, 0, 1, 2, 3, .. and they have type int.

Floats
Any number with a decimal point is a floating-point number. The term float
means that the decimal point can appear at any position in a number.

In general, you can use floats like integers. For example:

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Underscores in numbers
When a number is large, it’ll become difficult to read. For example:

To make the long numbers more readable, you can group digits using underscores, like this:

When storing these values, Python just ignores the underscores. It does so when displaying
the numbers with underscores on screen:

Boolean data type


In programming, you often want to check if a condition is true or not and
perform some actions based on the result.To represent true and false,
Python provides you with the boolean data type. The boolean value has a
technical name as bool. The boolean data type has two values: True and False.
Note that the boolean values True and False start with the capital letters ( T) and
(F). The following example defines two boolean variables:

Conversion in Python
To get an input from users, you use the input() function. For example:

Operators
Comparison
operators

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
In programming, you often want to compare a value with another value. To
do that, you use comparison operators. Python has six comparison operators,
which are as follows:

 Less than ( < )


 Less than or equal to (<=)
 Greater than (>)
 Greater than or equal to (>=)
 Equal to ( == )
 Not equal to ( != )

Logical operators
You may want to check multiple conditions at the same time. To do so, you
use logical operators.

Python has three logical operators:

 and
 or
 not

Task
1. What is a variable?
2. When should we use “”” (tripe quotes) to define strings?
3. Assuming (name = “John Smith”), what does name[1] return?
4. What about name[-2]?
5. What about name[1:-1]?
6. How to get the length of name?
7. What is the result of f“{2+2}+{10%3}”?
8. What are the 3 types of numbers in Python?
9. Write a program to get two number from user and print sum,
difference, module, division and multiplication of the numbers,
also show the type of the enter data.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Task
1. What is a
variable? Answer:
A variable in Python is a name that stores a value. It acts like a container
that holds data, which can be changed later.

Example:

2. When should we use “”” (tripe quotes) to define


strings? Answer:
Triple quotes (""" """ or ''' ''') are used when defining multi-line strings in Python.
Example:

3. Assuming (name = “John Smith”), what does name[1]


return? Answer:
name[1] returns the character at index 1 (Python starts counting from 0).

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
4. What about name[-2]?
Answer:

Negative indices count from the end. name[-2] means the second-to-last character.

5. What about name[1:-1]?


Answer:

6. How to get the length of


name? Answer:

7. What is the result of


f“{2+2}+{10%3}”? Answer:

The f"" string evaluates expressions inside {}.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
8. What are the 3 types of numbers in
Python? Answer:
The following are the 3 types of numbers in python
 int → Integer numbers (e.g., 10, -5)
 float → Decimal numbers (e.g., 3.14, -2.5)
 complex → Complex numbers (e.g., 2 + 3j)

9. Write a program to get two number from user and print sum, difference,
module, division and multiplication of the numbers, also show the type
of the enter data.

Answer:

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023

Output:

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023

Lab no 2
Loop and Conditional Statements in Python
Objectives:
 Introduction of loop and conditional statements.
 Demonstration of List, tuples and dictionary.
 Implementation of loop (while and for)
 Implementation of Conditional statements (if, if-else, if-else-if and switch)

Lists are just like dynamically sized arrays, declared in other languages (vector in C++
and ArrayList in Java). Lists need not be homogeneous always which makes it the most
powerful tool in Python. A single list may contain Datatypes like Integers, Strings, as
well as Objects. Lists are mutable, and hence, they can be altered even after their
creation.

# Creating a List
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# using index
List = ["Test", "For", "Test"]
print("\nList Items: ")
print(List[0])
print(List[2])

# (By Nesting a list inside a List)

Tuple is a collection of Python objects much like a list. The sequence of values stored
in a tuple can be of any type, and they are indexed by integers.
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# with the use of string


Tuple1 = ('Test', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which, unlike other Data Types that hold only a single value as an
element, Dictionary holds key:value pair. Key-value is provided in the dictionary to
make it more optimized.

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Test', 2: 'For', 3: 'Test'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a
Dictionary # with
Mixed keys
Dict = {'Name': 'Test', 1: [1, 2, 3, 4]}
print("\nDictionary
Decision with the use of Mixed
making statement:
IfKeys: ") print(Dict)
statements are control flow statements which helps us to run a particular code only
when a certain condition is satisfied. For example, you want to print a message on the
screen only when a condition is true then you can use if statement to accomplish this in
programming. In this guide, we will learn how to use if statements in Python
programming with the help of examples.
if condition:
block_of_code

flag = True
if flag==True:
print("Welcome")
print("To")
print("BeginnersBook.com")

flag = True
if flag:
print("Welcome")
print("To")
print("BeginnersBook.com")

If else Statement Example


if condition:
block_of_code_1
else:
block_of_code_2

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023

num = 22
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")

If elif else statement example


if condition:
block_of_code_1
elif condition_2:
block_of_code_2
elif condition_3:
block_of_code_3
..
..
..
else:
block_of_code_n

Notes:
1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is allowed.
2. Out of all these blocks only one block_of_code gets executed. If the condition is true
then the code inside ‘if’ gets executed, if condition is false then the next
condition(associated with elif) is evaluated and so on. If none of the conditions is true
then the code inside ‘else’ gets executed.
num = 1122
if 9 < num < 99:
print("Two digit number")
elif 99 < num < 999:
print("Three digit number")
elif 999 < num < 9999:
print("Four digit number")
else:
print("number is <= 9 or >= 9999")

Nested if..else statement example


num = -99
if num > 0:
print("Positive Number")
else:
print("Negative Number")
#nested if
if -99<=num:

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
print("Two digit Negative Number")

Loop:

Syntax of for loop in Python


for <variable> in <sequence>:
# body_of_loop that has set of statements
# which requires repeated execution
Here <variable> is a variable that is used for iterating over a <sequence>. On every
iteration it takes the next value from <sequence> until the end of sequence is reached.
# List of integer numbers
numbers = [1, 2, 4, 6, 11, 20]

# variable to store the square of each num temporary


sq = 0

# iterating over the given


list for val in numbers:
# calculating square of each number
sq = val * val
# displaying the
squares print(sq)
Function range()
In the above example, we have iterated over a list using for loop. However we can also
use a range() function in for loop to iterate over numbers defined by range().

range(n): generates a set of whole numbers starting from 0 to (n-1).


For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]

range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]

range(start, stop, step_size): The default step_size is 1 which is why when we didn’t
specify the step_size, the numbers generated are having difference of 1. However by
specifying step_size we can generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Lets use the range() function in for loop:

# variable to store the sum


sum = 0

# iterating over natural numbers using range()


for val in range(1, 6):
# calculating sum
sum = sum + val

# displaying sum of first 5 natural numbers


print(sum)

For loop with else block


Unlike Java, In Python we can have an optional ‘else’ block associated with the loop. The
‘else’ block executes only when the loop has completed all the iterations. Lets take an
example:

for val in range(5):


print(val)
else:
print("The loop has completed execution")

Nested For loop in Python


When a for loop is present inside another for loop then it is called a nested for loop.
Lets take an example of nested for loop.

for num1 in range(3):


for num2 in range(10, 14):
print(num1, ",", num2)

While Loop
While loop is used to iterate over a block of code repeatedly until a given condition
returns false.
The main difference is that we use while loop when we are not certain of the number of
times the loop requires execution, on the other hand when we exactly know how many
times we need to run the loop, we use for loop.
Syntax of while loop
while condition:
#body_of_while

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023

num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num <
10:
print(num)
#incrementing the value of
num num = num + 3
Nested while loop in Python
When a while loop is present inside another while loop then it is called nested while loop.
Lets take an example to understand this concept.

i=1
j=5
while i < 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1

Python – while loop with else block


We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It
executes only after the loop finished execution.

num = 10
while num >
6:
print(num)
num = num-1
else:
print("loop is finished")

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Task:
 Write code that reverses and sorts lists, dictionary and tuple.

 Write code the finds the largest or smallest element of a list.

 Print the following patterns using loop

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023

 Print multiplication table of 24, 50 and 29 using loop.

 Write a Python program that prints all the numbers from 0 to 6


except 3 and 6.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
 Write a Python program to sum all the items in a dictionary.

 Write a Python program to find the repeated items of a tuple.

 Write a Python program to replace last value of tuples in a


list. Sample list: [(10, 20, 40), (40, 50, 60), (70, 80,
90)]
Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023

Lab no 3
Function and class in Python
Objectives:
 What is function python?
 Implementation of function in python.
 Type of function in python?
 Implementation of function type.
 What is class?
 Implementation of class in python
 Implementation of constructor in python

Functions:
In Python, a function is a group of related statements that performs a specific task. Functions
help break our program into smaller and modular chunks. As our program grows larger and
larger, functions make it more organized and manageable. It avoids repetition and makes the
code reusable.

def function_name(parameters):

"""docstring"""

statement(s)

def my_function():
print("Hello from a
function")

Types of Functions
Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.

2. User-defined functions - Functions defined by the users themselves.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Arguments
Information can be passed into functions as arguments. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition. This way the function will receive a tuple of
arguments, and can access the items accordingly

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Keyword Arguments
You can also send arguments with the key = value syntax.This way the order of the arguments
does not matter.

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


Arbitrary Keyword Arguments, **kwargs

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
If you do not know how many keyword arguments that will be passed into your function, add
two asterisks: ** before the parameter name in the function definition. This way the function will
receive a dictionary of arguments, and can access the items accordingly:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Default Parameter Value


The following example shows how to use a default parameter value. If we call the function
without argument, it uses the default value:

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Class
Python is an object-oriented programming language. Unlike procedure-oriented programming,
where the main emphasis is on functions, object-oriented programming stresses on objects. An
object is simply a collection of data (variables) and methods (functions) that act on those data.
Similarly, a class is a blueprint for that object.

We can think of a class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
As many houses can be made from a house's blueprint, we can create many objects from a class.
An object is also called an instance of a class and the process of creating this object is
called instantiation.
class Person:
"This is a person
class" age = 10

def greet():
print('Hello')

# Output: 10
print(Person.age)

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
# Output: <function Person.greet>
print(Person.greet)

# Output: "This is a person class"


print(Person. doc )
Constructors in Python
Class functions that begin with double underscore are called special functions as they have
special meaning. Of one particular interest is the init () function. This special function gets
called whenever a new object of that class is instantiated. This type of function is also called
constructors in Object Oriented Programming (OOP). We normally use it to initialize all the
variables.
class Person:
def init (self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
The self-Parameter
The self-parameter is a reference to the current instance of the class, and is used to access variables
that belong to the class.

It does not have to be named self, you can call it whatever you like, but it has to be the first
parameter of any function in the class:

Delete Object Properties


You can delete properties on objects by using the Del keyword:

del p1.age

Delete Object Properties


You can delete properties on objects by using the Del keyword:

del p1

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Task:
1. Follow the steps:

 Create a class, Triangle. Its init () method should take self, angle1, angle2, and
angle3 as arguments. Make sure to set these appropriately in the body of the init
()method.

 Create a variable named number_of_sides and set it equal to 3.

 Create a method named check_angles. The sum of a triangle's three angles is It should
return True if the sum of self.angle1, self.angle2, and self.angle3 is equal 180, and False
otherwise.

 Create a variable named my_triangle and set it equal to a new instance of your Triangle
class. Pass it three angles that sum to 180 (e.g. 90, 30, 60).

 Print out my_triangle.number_of_sides and print out my_triangle.check_angles().

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
2. Import the math module in whatever way you prefer. Call its sqrt function on
the number 13689 and print that value to the console.

3. Follow the steps:

 First, def a function called cube that takes an argument called number.

 Make that function return the cube of that number (i.e. that number multiplied by itself
and multiplied by itself once again).

 Define a second function called by_three that takes an argument called number. if that
number is divisible by 3,by_threeshould call cube(number) and return its result.
Otherwise, by_three should return False. -Check if it works.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Lab no 4
Collection in python
Objectives:
 What is collection in python?
 Implementation of List, dictionary and tuples.
 Implementation of Json in python.
 Implementation of Numpy in python.
 Implementation of pandas in python.

Json:
JSON (JavaScript Object Notation) is a popular data format used for representing structured
data. It's common to transmit and receive data between a server and web application in
JSON format.
Python has a built-in package called json, which can be used to work with JSON data.

Import the json module:

import json

Convert from Python to JSON


If you have a Python object, you can convert it into a JSON string by using the
json.dumps() method.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023

When you convert from Python to JSON, Python objects are converted into the
JSON (JavaScript) equivalent:

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Convert from JSON to Python
If you have a JSON string, you can parse it by using the json.loads() method.

What is NumPy?
NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023

Pandas:
Pandas are an open-source, BSD-licensed Python library providing high-performance, easy-to-
use data structures and data analysis tools for the Python programming language. Python with
Pandas is used in a wide range of fields including academic and commercial domains including
finance, economics, Statistics, analytics, etc. We will learn the various features of Python Pandas
and how to use them in practice.
Key Features of Pandas
 Fast and efficient DataFrame object with default and customized indexing.
 Tools for loading data into in-memory data objects from different file formats.
 Data alignment and integrated handling of missing data.
 Reshaping and pivoting of date sets.
 Label-based slicing, indexing and subsetting of large data sets.
 Columns from a data structure can be deleted or inserted.
 Group by data for aggregation and transformations.
 High performance merging and joining of
data. Pandas deals with the following three data
structures

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
 Series
 DataFrame
 Panel
These data structures are built on top of Numpy array, which means they are fast.

Dimension & Description


The best way to think of these data structures is that the higher dimensional data structure is a
container of its lower dimensional data structure. For example, DataFrame is a container of
Series, Panel is a container of DataFrame.

Data Dimensions Description


Structure

Series 1 1D labeled homogeneous array, sizeimmutable.

Data 2 General 2D labeled, size-mutable tabular


Frame structure with potentially heterogeneously
s typed columns.

Panel 3 General 3D labeled, size-mutable array.

Building and handling two or more dimensional arrays is a tedious task, burden is placed on the
user to consider the orientation of the data set when writing functions. But using Pandas data
structures, the mental effort of the user is reduced.
For example, with tabular data (DataFrame) it is more semantically helpful to think of the
index (the rows) and the columns rather than axis 0 and axis 1.

Pandas Series
A pandas Series can be created using the following constructor

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
DataFrame
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with
rows and columns.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Task
1. Write a Python program to convert JSON data to Python object.

2. Write a Python program to convert Python object to JSON data.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023

3. Write a Python program to create a new JSON file from an existing JSON file.

4. Write a Python program to convert Python dictionary object (sort by key)


to JSON data. Print the object members with indent level 4.

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023

5. Write a NumPy program to create a 3x3 matrix with values ranging from
2 to 10. Expected Output:
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]

6. Write a NumPy program to convert a list and tuple


into arrays. List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]

Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
7. Write a Pandas program to add, subtract, multiple and divide two
Pandas Series. Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9].

Artificial Intelligence

You might also like