UNIT-5
1. Aim:- Python program to check whether a JSON string
contains complex object or not
Program:-
import ast
def is_complex_object(string):
"""Check if the string represents a complex object (list or
dict)."""
try:
obj = ast.literal_eval(string)
if isinstance(obj, (list, dict)):
return True
except (ValueError, SyntaxError):
pass
return False
def main():
test_strings = [
"[1,2,3]",
"{'key': 'value'}",
"1,2,3",
"'simple string'",
"3.14",
"not a complex obj",
"[{'a': 1}, {'b': 2}]"
]
for s in test_strings:
if is_complex_object(s):
print(f"The string '{s}' contains a complex object.")
else:
print(f"The string '{s}' does NOT contain a complex
object.")
if __name__ == "__main__":
main()
2. Aim:-Python program to demonstrate numpy arrays creations
using array() function
Program:-
import numpy as np
def create_arrays():
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(array_1d)
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(array_2d)
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(array_3d)
def main ():
create_arrays()
if __name__ == "__main__":
main ()
3. Aim:-Python program to demonstrate use to ndim, shape, size,
dtype.
Program: -
import numpy as np
def demonstrate_array_properties():
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(array_1d)
print("number of dimensions(ndim):",array_1d.ndim)
print("Shape:",array_1d.shape)
print("Size:",array_1d.size)
print("Data type(dtype):",array_1d.dtype)
print()
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(array_2d)
print("number of dimensions(ndim):",array_2d.ndim)
print("Shape:",array_2d.shape)
print("Size:",array_2d.size)
print("Data type(dtype):",array_2d.dtype)
print()
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(array_3d)
print("number of dimensions(ndim):",array_3d.ndim)
print("Shape:",array_3d.shape)
print("Size:",array_3d.size)
print("Data type(dtype):",array_3d.dtype)
print()
def main():
demonstrate_array_properties()
if __name__ == "__main__":
main()
4. Aim:-Python program to demonstrate basic slicing, integer
and Boolean indexing.
Program:-
import numpy as np
def demonstrate_indexing():
array_2d=np.array([1,2,3,4],[5,6,7,8],[9,10,11,12])
print("Original 2D array:")
print(array_2d)
print()
print("Basic Slicing:")
sliced_array=array_2d[1:3,1:4]
print(sliced_array)
print()
print("Integer Indexing:")
indexed_array=array_2d[[0,2],[1,3]]
print(indexed_array)
print()
print("Boolean Indexing:")
boolean_mask=array_2d>6
print(boolean_mask)
boolean_indexed_array=array_2d[boolean_mask]
print("Elements greater than 6:")
print(boolean_indexed_array)
def mani():
demonstrate_indexing()
if __name__=="__main__":
main()
5. Aim:-Python program to find min, max , sum, cumulative sum
of array.
Program:-
import numpy as np
def array_operations():
array=np.array([10,20,30,40,50])
min_value=np.min(array)
print("Minimum Value:",min_value)
max_value=np.max(array)
print("Maximum Value:",max_value)
total_sum=np.sum(array)
print("Sum od array:",total_sum)
cumulative_sum=np.cumsum(array)
print("Cumulative Sum:",cumulative_sum)
def main():
array_operations()
if __name__=="__main__":
main()
6. Aim:- Create a dictionary with at least five keys and each key
represents value as a list where this contains at least ten values
and converts this dictionary as a panda’s data frame and
explore the data through the data frame as follows:
a) Apply head() functions to the panda’s data frame.
b)Perform various data selection operations on data frame
Program:-
import pandas as pd
def create_and_explore_dataframe():
data={
'Name':
['Alice','Bob','Charlie','David','Eva','Frank','Grace','Hanah','Ian'
,'Julian'],
'Age':[24,30,22,35,28,40,29,31,25,26],
'City':['New York','Los
Angeles','Chicago','Houston','Phoenix','Philadelphia','San
Antonio','San Diego','Dallas','San Jose'],
'Salary':
[7000,8000,62000,90000,75000,120000,60000,72000,85000,9
5000],
'Department':
['HR','IT','Finance','Marketing','IT','HR','Finance','Marketing','I
T','Finance']
}
df=pd.DataFrame(data)
print("Data frame:")
print(df)
print("\nFirst 5 rows:")
print(df.head())
print("\n Selecting the 'Name' column:")
print(df['Name'])
print("\n Selecting multiple columns'Name' and 'Salary':")
print(df[['Name','Salary']])
print("\n Selecting rows where Age>30:")
print(df[df['Age']>30])
print("\nSelecting specific rows(1 to 3):")
#print(df[df['Age']>30])
#print("\n selecting rows ")
print(df.iolc[1:4])
print("\n Selecting using loc for specific rows and
columns:")
print(df.loc[2:5,['Name,city']])
def main():
create_and_explore_dataframe()
if __name__=="__main__":
main()
7. Aim:- Select any two columns from above data frame, and
observe the change in one attribute with respect to other
attribute with scatter and plot operations in matplotlib.
Program: -
import pandas as pd
def create_and_explore_dataframe():
data={
'Name':
['Alice','Bob','Charlie','David','Eva','Frank','Grace','Hanah','Ian'
,'Julian'],
'Age':[24,30,22,35,28,40,29,31,25,26],
'City':['New York', 'Los Angeles' ,'Chicago' ,
'Houston','Phoenix','Philadelphia','San Antonio','San
Diego','Dallas','San Jose'],
'Salary':[7000,8000,62000,90000,75000,120000,60000,
72000,85000,95000],
'Department':
['HR','IT','Finance','Marketing','IT','HR','Finance','Marketing','I
T','Finance']
}
df=pd.DataFrame(data)
print("Data frame:")
print(df)
selected_columns=df[['Age','Salary']]
print("\n Selected columns")
print(selected_columns)
plt.figure(fig size=(10,6))
plt.scatter(selected_columns['Age'],selected_columns['Salary']
)
plt.xlabel('Age')
plt.ylabel('Salary')
plt.title(scatter plot : salary vs Age)
plt.grid(True)
plt.show()
plt.figure(fig size=(10,6))
plt.plot(selected_columns['Age'],selected_columns['Salary'],
marker='0')
plt.xlabel('Age')
plt.ylabel('Salary')
plt.title(line plot : salary vs Age)
plt.grid(True)
plt.show()
def main():
create_and_explore_dataframe()
if __name__=="__main__":
main()