1.
Python program to check whether a JSON string contains complex object or not
Aim: Python program to check whether a JSON string contains complex object or not
Program:
import json
def contains_complex_object(json_str):
try:
data = [Link](json_str)
except [Link]:
return False, "Invalid JSON"
def is_complex(value):
if isinstance(value, (dict, list)):
return True
if isinstance(value, dict):
return any(is_complex(v) for v in [Link]())
if isinstance(value, list):
return any(is_complex(v) for v in value)
return False
return is_complex(data)
JsonStrings = [
'"Hello"', '123', 'true', 'null', '{"a": 1, "b": 2}', '[1, 2, 3]', '{"a": {"b": 2}}', ]
for jstring in JsonStrings:
print(f"{jstring} -> {contains_complex_object(jstring)}")
Output:
"Hello" -> False
123 -> False
true -> False
null -> False
{"a": 1, "b": 2} -> True
[1, 2, 3] -> True
{"a": {"b": 2}} -> True
2. Python Program to demonstrate NumPy arrays creation using array () function.
Aim: Python Program to demonstrate NumPy arrays creation using array () function.
Program:
import numpy as np
# Creating 1D array
arr1 = [Link]([1, 2, 3, 4, 5])
print("1D Array:")
print(arr1)
# Creating 2D array
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(arr2)
# Creating 3D array
arr3 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(arr3)
# Checking dimensions
print("\nDimensions of arr1:", [Link])
print("Dimensions of arr2:", [Link])
print("Dimensions of arr3:", [Link])
Ouput:
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Dimensions of arr1: 1
Dimensions of arr2: 2
Dimensions of arr3: 3
3. Python program to demonstrate use of ndim, shape, size, dtype
Aim: Python program to demonstrate use of ndim, shape, size, dtype
Program:
import numpy as np
# Creating arrays
arr1 = [Link]([1, 2, 3, 4, 5])
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
arr3 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Display array properties
print("1D Array:")
print(arr1)
print("ndim:", [Link])
print("shape:", [Link])
print("size:", [Link])
print("dtype:", [Link])
print("\n2D Array:")
print(arr2)
print("ndim:", [Link])
print("shape:", [Link])
print("size:", [Link])
print("dtype:", [Link])
print("\n3D Array:")
print(arr3)
print("ndim:", [Link])
print("shape:", [Link])
print("size:", [Link])
print("dtype:", [Link])
Output:
1D Array:
[1 2 3 4 5]
ndim: 1
shape: (5,)
size: 5
dtype: int64
2D Array:
[[1 2 3]
[4 5 6]]
ndim: 2
shape: (2, 3)
size: 6
dtype: int64
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
ndim: 3
shape: (2, 2, 2)
size: 8
dtype: int64
4. Python program to demonstrate basic slicing, integer and Boolean indexing.
Aim: Python program to demonstrate basic slicing, integer and Boolean indexing.
Program:
import numpy as np
# Creating a NumPy array
arr = [Link]([10, 20, 30, 40, 50, 60, 70])
print("Original Array:")
print(arr)
# 1. Basic Slicing
print("\nBasic Slicing:")
print("arr[1:5] ->", arr[1:5])
print("arr[:4] ->", arr[:4])
print("arr[3:] ->", arr[3:])
print("arr[::2] ->", arr[::2])
# 2. Integer Indexing
print("\nInteger Indexing:")
indices = [0, 2, 5]
print("Elements at indices [0, 2, 5] ->", arr[indices])
# 3. Boolean Indexing
print("\nBoolean Indexing:")
bool_arr = arr > 30 # condition
print("Boolean condition (arr > 30):", bool_arr)
print("Elements greater than 30:", arr[bool_arr])
Output:
Original Array:
[10 20 30 40 50 60 70]
Basic Slicing:
arr[1:5] -> [20 30 40 50]
arr[:4] -> [10 20 30 40]
arr[3:] -> [40 50 60 70]
arr[::2] -> [10 30 50 70]
Integer Indexing:
Elements at indices [0, 2, 5] -> [10 30 60]
Boolean Indexing:
Boolean condition (arr > 30): [False False False True True True True]
Elements greater than 30: [40 50 60 70]
5. Python program to find min, max, sum, cumulative sum of array
Aim: Python program to find min, max, sum, cumulative sum of array
Program:
import numpy as np
# Creating a NumPy array
arr = [Link]([10, 20, 30, 40, 50])
print("Array:", arr)
# Minimum element
print("Minimum:", [Link](arr))
# Maximum element
print("Maximum:", [Link](arr))
# Sum of elements
print("Sum:", [Link](arr))
# Cumulative sum
print("Cumulative Sum:", [Link](arr))
Output:
Array: [10 20 30 40 50]
Minimum: 10
Maximum: 50
Sum: 150
Cumulative Sum: [ 10 30 60 100 150]
6. 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: 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
Program:
import pandas as pd
import numpy as np
# 1. Create dictionary
data = {
"Name": ["Alice", "Bob", "Charlie", "David", "Eva", "Frank", "Grace", "Hannah", "Ian",
"Jack"],
"Age": [25, 30, 22, 35, 28, 24, 31, 27, 29, 26],
"City": ["NY", "LA", "SF", "NY", "LA", "SF", "NY", "LA", "SF", "NY"],
"Salary": [50000, 60000, 45000, 70000, 52000, 48000, 65000, 58000, 61000, 53000],
"Experience": [2, 5, 1, 8, 3, 2, 6, 4, 5, 3]
}
# 2. Convert dictionary to DataFrame
df = [Link](data)
# 3. Explore Data
# a) Apply head() function
print("First 5 rows of DataFrame:")
print([Link]())
# b) Data Selection Operations
print("\nSelect 'Name' column:")
print(df["Name"])
print("\nSelect multiple columns ('Name' and 'Salary'):")
print(df[["Name", "Salary"]])
print("\nSelect rows by index (first 3 rows):")
print(df[0:3])
print("\nSelect rows based on condition (Salary > 55000):")
print(df[df["Salary"] > 55000])
print("\nSelect rows using loc (row 2 to 4, columns 'Name' and 'City'):")
print([Link][2:4, ["Name", "City"]])
print("\nSelect rows using iloc (first 3 rows, first 2 columns):")
print([Link][0:3, 0:2])
Output:
First 5 rows of DataFrame:
Name Age City Salary Experience
0 Alice 25 NY 50000 2
1 Bob 30 LA 60000 5
2 Charlie 22 SF 45000 1
3 David 35 NY 70000 8
4 Eva 28 LA 52000 3
Select 'Name' column:
0 Alice
1 Bob
2 Charlie
3 David
4 Eva
5 Frank
6 Grace
7 Hannah
8 Ian
9 Jack
Name: Name, dtype: object
Select multiple columns ('Name' and 'Salary'):
Name Salary
0 Alice 50000
1 Bob 60000
2 Charlie 45000
3 David 70000
4 Eva 52000
5 Frank 48000
6 Grace 65000
7 Hannah 58000
8 Ian 61000
9 Jack 53000
Select rows by index (first 3 rows):
Name Age City Salary Experience
0 Alice 25 NY 50000 2
1 Bob 30 LA 60000 5
2 Charlie 22 SF 45000 1
Select rows based on condition (Salary > 55000):
Name Age City Salary Experience
1 Bob 30 LA 60000 5
3 David 35 NY 70000 8
6 Grace 31 NY 65000 6
7 Hannah 27 LA 58000 4
8 Ian 29 SF 61000 5
Select rows using loc (row 2 to 4, columns 'Name' and 'City'):
Name City
2 Charlie SF
3 David NY
4 Eva LA
Select rows using iloc (first 3 rows, first 2 columns):
Name Age
0 Alice 25
1 Bob 30
2 Charlie 22
7. Select any two columns from the above data frame, and observe the change in oneattribute
with respect to other attribute with scatter and plot operations in matplotlib
Aim: Select any two columns from the above data frame, and observe the change in
oneattribute with respect to other attribute with scatter and plot operations in matplotlib
Program:
import pandas as pd
import [Link] as plt
# Creating the DataFrame again
data = {
"Name": ["Alice", "Bob", "Charlie", "David", "Eva", "Frank", "Grace", "Hannah", "Ian",
"Jack"],
"Age": [25, 30, 22, 35, 28, 24, 31, 27, 29, 26],
"City": ["NY", "LA", "SF", "NY", "LA", "SF", "NY", "LA", "SF", "NY"],
"Salary": [50000, 60000, 45000, 70000, 52000, 48000, 65000, 58000, 61000, 53000],
"Experience": [2, 5, 1, 8, 3, 2, 6, 4, 5, 3]
}
df = [Link](data)
# Selecting two columns
x = df["Age"]
y = df["Salary"]
# --- Scatter Plot ---
[Link](figsize=(8,5))
[Link](x, y, color='blue', marker='o')
[Link]("Scatter Plot of Age vs Salary")
[Link]("Age")
[Link]("Salary")
[Link](True)
[Link]()
# --- Line Plot ---
[Link](figsize=(8,5))
[Link](x, y, color='green', marker='x', linestyle='--')
[Link]("Line Plot of Age vs Salary")
[Link]("Age")
[Link]("Salary")
[Link](True)
[Link]()
Output: