0% found this document useful (0 votes)
2 views12 pages

UNIT 5PythonLabManual

The document outlines a series of Python programming experiments focused on using NumPy and Pandas for data manipulation and analysis. It includes examples of creating and manipulating NumPy arrays, performing operations like slicing and indexing, and creating DataFrames from dictionaries. Additionally, it demonstrates data visualization techniques using Matplotlib and checks for complex objects in JSON strings.

Uploaded by

waseemshaikaa
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)
2 views12 pages

UNIT 5PythonLabManual

The document outlines a series of Python programming experiments focused on using NumPy and Pandas for data manipulation and analysis. It includes examples of creating and manipulating NumPy arrays, performing operations like slicing and indexing, and creating DataFrames from dictionaries. Additionally, it demonstrates data visualization techniques using Matplotlib and checks for complex objects in JSON strings.

Uploaded by

waseemshaikaa
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

UNIT-V

JSON,XML,NUMPY,PANDAS

Experiment 24: Python Program to demonstrate NumPy arrays creation using array () function.

Aim: To write a Python program to demonstrate NumPy array creation using the array() function.

Algorithm:

1. Start.
2. Import the numpy module as np.
3. Create a 1D NumPy array using the [Link]() function.
4. Create a 2D NumPy array using a list of lists.
5. Display the created arrays.
6. Print the array types and dimensions using the .dtype and .ndim attributes.
7. End.

Program:
# Step 1: Import numpy module
import numpy as np

# Step 2: Create 1D array


arr1 = [Link]([10, 20, 30, 40, 50])
print("1D Array:")
print(arr1)

# Step 3: Create 2D array


arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(arr2)

# Step 4: Display details


print("\nType of arr1:", type(arr1))
print("Data type of arr1 elements:", [Link])
print("Number of dimensions of arr2:", [Link])
print("Shape of arr2:", [Link])

Output:

1D Array:

[10 20 30 40 50]
2D Array:

[[1 2 3]

[4 5 6]]

Type of arr1: <class '[Link]'>

Data type of arr1 elements: int64

Number of dimensions of arr2: 2

Shape of arr2: (2, 3)

Result:

The program successfully demonstrates the creation of 1D and 2D NumPy arrays using the array() function and displays
their properties such as type, data type, dimensions, and shape.

Experiment 25: Python program to demonstrate use of ndim, shape, size, dtype.

Aim:

To write a Python program to demonstrate the use of NumPy attributes — ndim, shape, size, and dtype

Algorithm:

1. Start.
2. Import the numpy module as np.
3. Create NumPy arrays (1D and 2D) using the [Link]() function.
4. Use the following NumPy array attributes:
5. ndim → to get the number of dimensions.
6. shape → to get the number of rows and columns.
7. size → to get the total number of elements.
8. dtype → to get the data type of elements.
9. Display all these attributes for the arrays.
10. End.

Program:

# Step 1: Import numpy module


import numpy as np

# Step 2: Create 1D array


arr1 = [Link]([10, 20, 30, 40, 50])

# Step 3: Create 2D array


arr2 = [Link]([[1, 2, 3], [4, 5, 6]])

# Step 4: Display array properties


print("1D Array:", arr1)
print("Number of Dimensions (ndim):", [Link])
print("Shape:", [Link])
print("Size:", [Link])
print("Data Type (dtype):", [Link])

print("\n2D Array:\n", arr2)


print("Number of Dimensions (ndim):", [Link])
print("Shape:", [Link])
print("Size:", [Link])
print("Data Type (dtype):", [Link])

Output:

1D Array: [10 20 30 40 50]

Number of Dimensions (ndim): 1

Shape: (5,)

Size: 5

Data Type (dtype): int64

2D Array:

[[1 2 3]

[4 5 6]]

Number of Dimensions (ndim): 2

Shape: (2, 3)

Size: 6

Data Type (dtype): int64

Result:

The program successfully demonstrates the use of NumPy array attributes — ndim, shape, size, and dtype, to
obtain structural and data-type information of arrays.

Experiment 26: Write a program to create, display, append, insert and reverse the order of the items in the array.
Aim: To write a Python program to demonstrate basic slicing, integer indexing, and Boolean indexing using NumPy arrays.
Algorithm:
1. Start.
2. Import the NumPy module as np.
3. Create a NumPy array using the [Link]() function.
4. Perform basic slicing using the syntax array[start:end:step].
5. Use integer indexing to access specific elements or subarrays.
6. Use Boolean indexing to extract elements that satisfy certain conditions.
7. Display all the results.
8. End.

Program:

# Step 1: Import numpy module


import numpy as np

# Step 2: Create a 1D array


arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80])

print("Original Array:", arr)

# Step 3: Basic slicing [start:end:step]


print("\nBasic Slicing Examples:")
print("Elements from index 2 to 6:", arr[2:7])
print("Every second element:", arr[::2])
print("Reverse array:", arr[::-1])

# Step 4: Integer indexing


print("\nInteger Indexing Examples:")
indices = [0, 2, 5]
print("Elements at positions 0, 2, and 5:", arr[indices])

# Step 5: Boolean indexing


print("\nBoolean Indexing Examples:")
bool_arr = arr > 40
print("Boolean condition (arr > 40):", bool_arr)
print("Elements greater than 40:", arr[bool_arr])

Output:
Original Array: [10 20 30 40 50 60 70 80]

Basic Slicing Examples:


Elements from index 2 to 6: [30 40 50 60 70]
Every second element: [10 30 50 70]
Reverse array: [80 70 60 50 40 30 20 10]

Integer Indexing Examples:


Elements at positions 0, 2, and 5: [10 30 60]

Boolean Indexing Examples:


Boolean condition (arr > 40): [False False False False True True True True]
Elements greater than 40: [50 60 70 80]
Result:

The program successfully demonstrates basic slicing, integer indexing, and Boolean indexing in NumPy arrays for efficient
element selection and filtering.

Experiment 27: Python program to find min, max, sum, cumulative sum of array

Aim:

To write a Python program to find the minimum, maximum, sum, and cumulative sum of elements in a NumPy array.

Algorithm:

1. Start.
2. Import the NumPy module as np.
3. Create a NumPy array using the [Link]() function.
4. Find the minimum value using the [Link]() function.
5. Find the maximum value using the [Link]() function.
6. Find the sum of all elements using the [Link]() function.
7. Find the cumulative sum using the [Link]() function.
8. Display all the results.
9. End.

Program:

# Step 1: Import numpy module

import numpy as np

# Step 2: Create an array

arr = [Link]([10, 20, 30, 40, 50])

# Step 3: Perform operations

minimum = [Link](arr)

maximum = [Link](arr)

total_sum = [Link](arr)

cumulative_sum = [Link](arr)

# Step 4: Display results


print("Array:", arr)

print("Minimum Value:", minimum)

print("Maximum Value:", maximum)

print("Sum of Elements:", total_sum)

print("Cumulative Sum:", cumulative_sum)

Output:

Array: [10 20 30 40 50]

Minimum Value: 10

Maximum Value: 50

Sum of Elements: 150

Cumulative Sum: [ 10 30 60 100 150]

Result:
The program successfully computes the minimum, maximum, sum, and cumulative sum of elements in a NumPy array using
built-in NumPy functions.

Experiment 28: Create a dictionary with at least five keys and each key represent value as a list where this
list contains at least ten values and convert this dictionary as a pandas data frame 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
Aim:

To write a Python program that creates a dictionary with lists as values, converts it into a Pandas DataFrame, and
explores the data using the head() function and data selection operations.

Algorithm:

1. Start.
2. Import the pandas library.
3. Create a dictionary with at least five keys, each containing a list of ten values.
4. Convert the dictionary into a Pandas DataFrame using [Link]().
5. Display the first few rows using the head() function.
6. Perform data selection operations using:
7. Column selection
8. Row selection using loc and iloc
9. Conditional selection
10. Display the results.
11. End.
Program:

# Step 1: Import pandas


import pandas as pd

# Step 2: Create a dictionary with lists


data = {
'Name': ['Ravi', 'Sita', 'John', 'Asha', 'Kiran', 'Lina', 'David', 'Meena', 'Ramesh', 'Tina'],
'Age': [21, 22, 23, 22, 24, 21, 23, 22, 25, 24],
'Department': ['CSE', 'ECE', 'IT', 'CSE', 'CIVIL', 'MECH', 'IT', 'ECE', 'CSE', 'IT'],
'Marks': [85, 78, 92, 88, 76, 69, 81, 90, 87, 79],
'City': ['Delhi', 'Hyderabad', 'Mumbai', 'Chennai', 'Pune', 'Delhi', 'Kolkata', 'Chennai', 'Hyderabad', 'Pune']
}

# Step 3: Convert dictionary to DataFrame


df = [Link](data)

# Step 4: Display the first few rows


print("---- Head of DataFrame ----")
print([Link]())

# Step 5: Perform data selection operations


print("\n---- Select a single column (Name) ----")
print(df['Name'])

print("\n---- Select multiple columns (Name and Marks) ----")


print(df[['Name', 'Marks']])

print("\n---- Select rows by index using iloc (first 3 rows) ----")


print([Link][0:3])

print("\n---- Select specific rows and columns using loc ----")


print([Link][0:4, ['Name', 'Department', 'Marks']])

print("\n---- Conditional Selection: Students with Marks > 85 ----")


print(df[df['Marks'] > 85])

Output

---- Head of DataFrame ----

Name Age Department Marks City

0 Ravi 21 CSE 85 Delhi

1 Sita 22 ECE 78 Hyderabad

2 John 23 IT 92 Mumbai
3 Asha 22 CSE 88 Chennai

4 Kiran 24 CIVIL 76 Pune

---- Select a single column (Name) ----

0 Ravi

1 Sita

2 John

3 Asha

4 Kiran

5 Lina

6 David

7 Meena

8 Ramesh

9 Tina

Name: Name, dtype: object

---- Select multiple columns (Name and Marks) ----

Name Marks

0 Ravi 85

1 Sita 78

2 John 92

3 Asha 88

4 Kiran 76

5 Lina 69

6 David 81

7 Meena 90
8 Ramesh 87

9 Tina 79

---- Select rows by index using iloc (first 3 rows) ----

Name Age Department Marks City

0 Ravi 21 CSE 85 Delhi

1 Sita 22 ECE 78 Hyderabad

2 John 23 IT 92 Mumbai

---- Select specific rows and columns using loc ----

Name Department Marks

0 Ravi CSE 85

1 Sita ECE 78

2 John IT 92

3 Asha CSE 88

4 Kiran CIVIL 76

---- Conditional Selection: Students with Marks > 85 ----

Name Age Department Marks City

2 John 23 IT 92 Mumbai

3 Asha 22 CSE 88 Chennai

7 Meena 22 ECE 90 Chennai

8 Ramesh 25 CSE 87 Hyderabad

Result:
The program successfully creates a dictionary, converts it into a Pandas DataFrame, and explores the data using the head()
function and various data selection operations.
Experiment 29: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.

Aim:

To write a Python program to select any two columns from a Pandas DataFrame and observe the change in
one attribute with respect to another using scatter and plot operations in Matplotlib.

Algorithm:

1. Start.
2. Import the required libraries: pandas and [Link].
3. Create a dictionary with sample data.
4. Convert the dictionary into a Pandas DataFrame.
5. Select two columns from the DataFrame (e.g., Age and Marks).
6. Use Matplotlib to:
7. Create a scatter plot between the two columns.
8. Create a line plot to visualize the trend.
9. Label the axes and add a title to both plots.
10. Display the plots.
11. End.

Program:

# Step 1: Import required libraries


import pandas as pd
import [Link] as plt

# Step 2: Create a dictionary with sample data


data = {
'Name': ['Ravi', 'Sita', 'John', 'Asha', 'Kiran', 'Lina', 'David', 'Meena', 'Ramesh', 'Tina'],
'Age': [21, 22, 23, 22, 24, 21, 23, 22, 25, 24],
'Department': ['CSE', 'ECE', 'IT', 'CSE', 'CIVIL', 'MECH', 'IT', 'ECE', 'CSE', 'IT'],
'Marks': [85, 78, 92, 88, 76, 69, 81, 90, 87, 79],
'City': ['Delhi', 'Hyderabad', 'Mumbai', 'Chennai', 'Pune', 'Delhi', 'Kolkata', 'Chennai', 'Hyderabad', 'Pune']
}

# Step 3: Convert dictionary to DataFrame


df = [Link](data)

# Step 4: Display the DataFrame


print("DataFrame:")
print(df)

# Step 5: Select two columns (Age vs Marks)


x = df['Age']
y = df['Marks']

# Step 6: Scatter Plot


[Link](figsize=(6,4))
[Link](x, y, color='blue', marker='o')
[Link]('Scatter Plot - Age vs Marks')
[Link]('Age')
[Link]('Marks')
[Link](True)
[Link]()

# Step 7: Line Plot


[Link](figsize=(6,4))
[Link](x, y, color='green', marker='*', linestyle='--')
[Link]('Line Plot - Age vs Marks')
[Link]('Age')
[Link]('Marks')
[Link](True)
[Link]()

Output

 Scatter Plot: Displays data points showing how Marks change with respect to Age.

 Line Plot: Displays a connected line showing the trend between Age and Marks.

Both plots will visually represent how students’ marks vary with their ages.

Result:
The program successfully selects two columns (Age and Marks) from the DataFrame and visualizes the relationship between
them using Matplotlib scatter and line plots.

Experiment 30: Python program to check whether a JSON string contains complex object or not.

Aim:

To write a Python program to check whether a JSON string contains a complex object or not.

Algorithm:

1. Start.
2. Import the json module.
3. Read a JSON string as input from the user or define it in the program.
4. Parse the JSON string into a Python object using [Link]().
5. Define a function to recursively check if the parsed JSON contains any complex objects such as Python
objects, sets, or custom classes.
6. If a complex type (like dictionary containing another dictionary, list of dicts, etc.) is found, display “JSON
contains complex object.”
7. Otherwise, display “JSON does not contain complex object.”
8. End.
Program:

# Step 1: Import the module


import json

# Step 2: Function to check for complex objects


def has_complex_object(obj):
if isinstance(obj, (dict, list)):
for value in ([Link]() if isinstance(obj, dict) else obj):
if isinstance(value, (dict, list)):
return True or has_complex_object(value)
return False

# Step 3: Input JSON string


json_string = '{"name": "Satish", "age": 25, "address": {"city": "Hyderabad", "pincode": 500001}}'

# Step 4: Convert JSON string to Python object


data = [Link](json_string)

# Step 5: Check for complex object


if has_complex_object(data):
print("JSON contains complex object.")
else:
print("JSON does not contain complex object.")
Output

JSON contains complex object.

Result:

The program successfully checks whether a given JSON string contains a complex object (such as nested dictionaries or lists).

You might also like