0 ratings 0% found this document useful (0 votes) 7 views 14 pages Unit 5 Python Programs
The document contains multiple Python programs demonstrating various functionalities, including checking for complex JSON objects, creating NumPy arrays, and performing operations on them such as slicing, indexing, and calculating statistics. It also includes a program for creating a dictionary and converting it into a Pandas DataFrame, along with data selection and exploration techniques. Additionally, it suggests using scatter plots to observe relationships between attributes in the DataFrame.
AI-enhanced title and description
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Sample Experiments:
1. Python program to check whether a JSON string contains complex object ornot.
‘You can check whether a ISON string contains a complex object (such as a nested dictionary or
list) in Python by first converting the ISON string into a Python object using [Link](, and then
checking if the resulting object is a dictionary or list, which are considered complex types in JSON.
Example Program:
geet
import json
defis_complex_json(jsou_string):
uy:
# Parse the JSON string into a Python object
parsed. json = [Link](json_siring)
# Cheek ifthe object is a dictionary or list (complex types)
if isinstance(parsed_json, (dict, list)):
return True
else:
return False
except json. JSONDecodeEnor:
# Ifthe string is not a valid ISON, return False
return False
# Test cases
json_str] ="{*name": "Alice", "age": 30}# Complex JSON (dictionary)
jsou_sti2 =""Hello World" Simple JSON (string)
json_stt3 ='[1, 2, 3, 4]# Complex JSON (list)
print(is_complex_json(json_str1))# True
print(is_complex_json(json_str2))# False
print(is_complex.json(json_str3))# TrueExplanation:
«The [Link]() function is used to convert a TSON string into a Python object
+ Ifthe resulting object is a dict or lst, it's considered a complex type in JSON, so the
fimction returns True.
« Ifit’s a simple type (like a string, number, or boolean), the function returns False.
+ Ifthe JSON string is invalid, a JSONDecodeEror is caught, and the function returns
False.
2. Python Program to demonstrate NumPy arrays ereation using array () function,
Here is a Python program that demonstrates how to create NumPy arrays using the
array() fimetion from the NumPy library.
Example Program:
import numpy as np
# Creating a 1D NumPy array using a list
array_1d=[Link]({1, 2, 3, 4, 5])
print("1D Amay:")
print(array_14)
# Creating a 2D NumPy array using a nested list
array_2d=[Link]({[1, 2,3], (4, 5, 6]))
print("\w2D Array")
print(array_24)
# Creating a 3D NumPy aray using a nested list
amay_3d=[Link](([[1, 2}, [3, 41} (5. 6), (7, 811)
print@\n3D Array:”)
print(array_3d)
# Creating an array of floats
float_aray = npanray({1.1, 2.2, 3.3, 4.4])
print("\Arrey of Floats:")
print(flost_aray)
# Creating an array with a specified data type
int_array = np array([1.2, 3, 4], dtype~'int32')
print("\wArray with a specified data type (ant32):")
2print nt_array)
Explanation:
1
2
3
4
5
1D Array: A single-dimensionel array is created from a simple list.
2D Array: A two-dimensional array is created from a nested list (List of lists)
3D Array: A three-dimensional array is created from a deeply nested list (list of lists of
lists)
Float Array: This demonstrates creating an aay with floating-point values.
Array with specified data type: The dtype parameter is used to specify the data type of
the array, in this case, int32
Output:
1D Array:
[12345]
2D Amray:
(fH 23]
[456]
3D Anay:
ff 2]
Bal)
{Is 6]
(78
Array of Floats:
[[Link]]
Array with a specified data type (int32)
[1234]3. Python program to demonstrate use of ndim,[Link],dtype.
Here is a Python program demonstrating the use of the ndim, shape, size, and dtype attributes of
a NumPy array.
Example Progr
import numpy as np
# Creating a 2D NumPy array
array_2d=nparray({[1, 2, 3), [4 5, 61])
print("Amay:")
print(anay_2d)
#ndim: Retums the number of dimensions of the array
print("inNumber of dimensions (ndim):", array_2d.ndim)
# shape: Refums a tuple of the array’s dimensions (rows, columns)
print("Shape of the array (shape):", array_2¢.shape)
# size: Returns the total number of elements in the array
print("Total number of elements (size):", array [Link])
# dtype: Retums the data type of the elements in the array
print("Data type of the array elements (dtype):", amay_2d dtype)Explanation of Attributes:
1. ndim: This returns the number of dimensions in the array. A 2D array has 2 dimensions,
a 3D array has 3 dimensions, ete.
2. shape: This returns a tuple that represents the shape of the array (ie., number of rows and
columns for 2D arrays). In this example, the shape will be (2, 3) because the array has 2
rows and 3 columns.
3. size: This gives the total number of elements in the array. In the example, it's 2* 3= 6.
4, dtype: This retums the data type of the elements in the arzay. In the example, since the
array contains integers, the data type will be int64 or int32. (depending on the system)
Output:
Anray:
23]
[456]
Number of dimensions (ndim): 2
Shape of the array (shape): (2, 3)
Total number of elements (size): 6
Data type of the array clements (dtype): int644. Python program to demonstrate basic slicing,integer and Boolean indexing.
Here's a Python program that demonsirates basic slicing, integer indexing, and Boolean
indexing using NumPy arrays.
Example Progr
import numpy as np
# Creating a 2D NumPy array
array_2d = [Link](([10, 20, 30], [40, 50, 60], [70, 80, 90])
print(*Amra
print(atray_2d)
# 1. Basie Slicing
print("\wBasic Slicing:")
# Extract a sub-array (first two rows, and first two columns)
sub_array = array 24{0:2, 0:2]
print("Sub-array (first two rows and columns)
print(sub_array)
# Extract all rows but only the second column
second_column = array 2d{:, 1]
print("\nSecond column")
print(second_column)
#2. Integer Indexing
print("\wluteger Indexing")
# Access specific elements using integer indexing
element = aay 2d{1, 2}# Element from 2nd row and 3rd column,
print(£"Element at position (1, 2): {elemeut}")
# Access multiple elements (e.g.. Ist row, 2nd and 3rd columns)
elements = array 2¢f0, (1, 2]]
print("Elements from the first row, second and third columns:
print(elements)
#3. Boolean Indexing
print("\nBoolean Indexing:")
# Create a Boolean condition to find elements greater than 50
bool_condition = array_2d>50
print("Boolean condition (elements greater than 50):")
print(bool_condition)
# Extract elements that satisfy the Boolean condition
greater_than_50=array 2dfarray 24> 50]
6print("\nElements greater than 50:")
print(greater_than_S0)
Explanation:
1. Basie Slicing
© amay_2d{0:2, 0:2]: Extracts a sub-aray that includes the first two rows and first
two columns,
© amtay_2df:, 1]: Extraets all rows but only the second column.
2. Integer Indexing:
© amray_2dfl, 2]: Accesses the element at the 2nd row and 3rd column,
© amay_2d{0, [1, 2}]: Retrieves multiple elements from the first row, specifically the
2nd and 3rd columns.
3. Boolean Indexing:
© amray_2d > 50: Creates a Boolean array where each element is compared agninst
the condition (greater than 50)
© amay_2dfarray 2d > 50]: Retrieves elements from the anay that are greater than
S0using Boolean indexing,
Array:
[[10 20 30]
[40 50 60]
[70 80 90})
Basic Slicing:
Sub-array (first two rows and columns).
[[10 20}
[40 50]
Second column:
[20 50 80]
Integer Indexing:
Element at position (1, 2): 60
Elements from the first row, second and third columns:
[20 30]
Boolean Indexing:
Boolean condition (clements greater than 50):
[False False False]
[False FalseTmue]
[ TrueTrueTrue]]
Elements greater than SO:[60 70 80 90]
5. Python program to find min, max,sum,cumulative sum of array
Here isa Python program that demonstrates how to find the minimum (min), maximum (max),
sum, and cumulative sum of elements in a NumPy array.
Example Program:
import numpy as np
# Creating a 1D NumPy array
array_ld=[Link]((10, 20, 30, 40, 50)
print("Array")
print(array_1d)
# Finding the minimum value in the array
min_value =[Link](array_1d)
print("\oMinimum value:", min_value)
# Finding the maximum value in the array
max_value = [Link](array_1d)
print("Maximum value:", max_valte)
# Finding the sum of all elements in the array
sum_valne = np snm(array_1d)
print("Sum of all elements:", sum_value)
# Finding the cumulative sum of elements in the array
cumulative_sum — [Link](array_1d)
print(Cumalative sum of elements:")
print(cumulative_sum)
Explanation:
Beppe
[Link]: Retums the minimum value from the array
[Link](): Retums the maximum value from the array.
[Link](): Returns the sum of all the elements in the array.
[Link](): Returns the cumulative sum of elements, where each element is the sum
of all preceding elements in the array.Output:
Array:
[10 20 30 40 50]
Minimum value: 10
‘Maxim value: 50
Sum of all elements: 150
Cumulative sum of elements:
[ 103060 100 150]
6 . Create a dictionary with at least five keys and each key representing a list where this list
contains at least ten values, and conver this dictionary into a pandas DataFrame and explore the
data through the Data Frame as follows:
a) Apply head( )function to the pandas data frame
b) Perform various data selection operations on Data Frame
Here's how you can create a dictionary where each key has a list of values, convert it into
a Pandas Data Frame, and perform various data selection operations.
Example Program:
import pandas as pd
# Creating a dictionary with five keys, each having @ list of ten values
data = {
‘Name’: [‘Alice', 'Bob’, ‘Charlie’, ‘David’, Eva’, ‘Frank’, 'Grace', ‘Hannah’, 'Ivy’, ‘Jack'],
‘Age’: [25, 30, 35, 28, 22, 33, 29, 24, 31, 27],
‘City: [New York, Los Angeles, ‘Chicago’, ‘Houston’, Phoenix’, Philadelphia’, ‘San Antonio’,
‘San Diego’, ‘Dallas’, ‘Austin'],
‘Salary’: [70000, 80000, 75000, 72000, 68000, 81000, 74000, 76000, 79000, 73000],
‘Department’: ['HR', Finance’, IT’, Marketing’, 'Sales’, "HR', Finance’, TT’, ‘Marketing’, 'Sales’]
}
# Converting the dictionary into a Pandas DataFrame
df= [Link](data)
# Exploring the data through the DataFrameprint(’DataFrame:")
print(df)
# a) Apply head() fiction to display the first 5 rows of the DataFrame
print("\nApplying head() function:")
print(df-head())
+b) Performing various data selection operations
# Selecting a single column (e.g., 'Name')
print("\nSelecting the ‘Name’ column")
print(d{'Name'])
# Selecting multiple columns (¢.g., ‘Name’ and 'Salary’)
print("\nSelecting ‘Name’ and 'Salary' columns:")
print(df{[/'Name', 'Salary']))
# Selecting rows based on a condition (¢.g., Salary greater than 75000)
print("\nRows where Salary is greater than 75000:")
print(df]dff'Salary’] > 75000)
# Selecting rows based on multiple conditions (e
‘Finance')
print("\nRows where Age > 30 and Department is ‘Finance’
print(dif(cf['Age'] > 30) & (di[’Department!] — "Finance’)))
Age greater than 30 and Department is
# Selecting rows by index (eg. first three 1ows)
print("nSelecting first three rows:")
print([Link]{:3])
Explanation:
1. Dictionary: A dictionary data is created with five keys: ‘Name’, 'Age', ‘City’, ‘Salary’, and
‘Department’. Each key las @ list of 10 values.
Pandas DataFrame: The dictionary is converted to a Pandas DataFrame using
[Link](data).
3. Head function (head()): Displays the first 5 rows of the DataFrame.
4, Data selection operations:
Selecting a single column: The ‘Name’ column is selected using df{'Name'].
© Selecting multiple columns: Both 'Name' and ‘Salary’ columns are selected using
af][’Name’, ‘Salary’.
© Conditional selection: Rows where the 'Salary’ is greater than 75000 are selected
using df{dfl'Salary’] > 75000).
2 Multiple conditions: Rows where 'Age' is greater than 30 and ‘Department is,
‘Finance’ are selected using df{(dfl'Age]] > 30) & (df]'Department ] = 'Finance’)]
© Selecting rows by index: The first 3 rows are selected using df'iloc[:3]
10DataFrame:
Name Age City Salary Department
0 Alice 25 New York 70000 HR
1 Bob 30 Los Angeles 80000 Finance
2 Charlie 35 Chicago 75000 IT
3 David 28 Houston 72000 Marketing
4 Eva 22 Phoenix 68000 Sales
5 Frank 33 Philadelphia 81000 HR
6 Grace 29 San Antonio 74000 Finance
7 Hannah 24 SanDiego 76000 IT
8 Ivy 31 Dallas 79000 Marketing
9 Tock 27 Austin 73000 Sales
Applying head() function:
Name Age City Salary Department
0 Alice 25 New York 70000 HR
1 Bob 30 Los Angeles 80000 Finance
2 Charlie 35 Chicago 75000 IT
3 Devid 28 Houston 72000 Marketing
4 Eva 22 Phoemx 68000 Sales
Selecting the Name’ column:
0 Alice
1 Bob
2 Chaulie
3 David
4 Eva
5S Frank
6 Grace
7 Hannah
8 by
9 Jack
‘Name: Name, dtype: object
Selecting ‘Name’ and ‘Salary’ columns
Name Salary
0 Alice 70000
1 Bob 80000
2 Charlie 75000
ulDavid 72000
Eva 68000
Frank 81000
Grace 74000
Hannah 76000
Ivy 79000
Jack 73000
Ceuauan
‘Rows where Salary is greater than 75000:
Name Age City Salary Department
Bob 30 LosAngeles 80000 Finance
Frank 33 Philadelphia 81000 HR
Hannah 24 San Diego 76000 IT
Ivy 31 Dallas 79000 Marketing
Rows where Age> 30 and Department is ‘Finance’:
Name Age City Salary Department
1 Bob 30 Los Angeles 80000 Finance
6 Grace 29 San Antonio 74000 Finance
Selecting first three rows:
Name Age City Salary Department
0 Alice 25 New York 70000 HR
1 Bob 30Los Angeles 80000 Finance
2 Charlie 35 Chicago 75000 Ir
127. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib.
Here's how you can select two columas from the previously created DataFrame and
observe the change in one attribute with respect to another using scatter and plot
operations with matplotlib
Example Progra
impo:t [Link] as plt
# Selecting two columns: ‘Age’ and ‘Salary’
age=df'Age]
salary = df{'Salary’]
# Scatter plot to observe the relationship between Age and Salary
[Link](figsize-(8, 5))
plt-scatter(age, salary, color="bine!, marker—'o')
# Adding labels and title
pltstitle(Scatter Plot: Age vs Salary’)
[Link](‘Age’)
pltylabel(Salary’)
# Display the scatter plot
pltshow
# Line plot to observe the trend between Age and Salary
[Link](figsize=(8, 5))
[Link](age, salary, colorgreen’, marker='0', linestyle='-)
# Adding labels and title
[Link](Line Plot: Age vs Salary’)
pltxlabel(‘Age')
plt-ylabel(Selary’)
# Display the line plot
plt.show0
13Explanation:
1. Scatter Plot: The scatter plot shows how salary varies with respect to age using the
[Link]() function. Each point represents a person’s age and salary.
© age is on the x-axis, and salary is on the y-axis
2. Line Plot: The line plot shows the trend between age and salary using the [Link]()
function. It counects the points in the scatter plot with a line.
3. [Link]: Used for creating visualizations like scatter and line plots,
Output:
1. Scatter Plot
2 The scatter plot displays the distribution of salaries across different ages, helping
to visually identify any correlation between the two
2. Line Plot:
© The line plot shows the general trend of how salary changes as age increases. The
points are connected by lines, helping to see how salary behaves across different
age values.
‘These plots help you visually observe the relationship between Age and Salary.
Age vs Salary Age vs Salary
Line Plot
re
14