-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnit-5
More file actions
131 lines (112 loc) · 4.32 KB
/
Copy pathUnit-5
File metadata and controls
131 lines (112 loc) · 4.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
24) #complex object or not
import json
def is_complex_json(json_string):
def check_complex(obj):
if isinstance(obj, (dict, list)):
return any(isinstance(item, (dict, list)) or check_complex(item) for item in (obj.values() if isinstance(obj, dict) else obj))
return False
try:
data = json.loads(json_string)
return check_complex(data)
except json.JSONDecodeError:
print("Invalid JSON string.")
return False
json_string = '{"name": "John", "address": {"city": "New York", "zipcode": "10001"}, "hobbies": ["reading", "sports"]}'
print("Contains complex object:", is_complex_json(json_string))
25) #NumPy arrays creation using array
import numpy as np
a_1d = np.array([1, 2, 3, 4, 5])
a_2d = np.array([[1, 2, 3], [4, 5, 6]])
a_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("1D Array:\n", a_1d)
print("\n2D Array:\n", a_2d)
print("\n3D Array:\n", a_3d)
26)
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
print("Number of dimensions (ndim):", a.ndim)
print("Shape of the array (shape):", a.shape)
print("Total number of elements (size):", a.size)
print("Data type of elements (dtype):", a.dtype)
print("Size of each element (itemsize):", a.itemsize)
27)
import numpy as np
# Creating a 2D array
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(arr)
# Row selection
print("\nFirst row:", arr[0])
print("Second row:", arr[1])
# Column selection
print("\nFirst column:", arr[:, 0])
print("Second column:", arr[:, 1])
# Slicing the array to extract a sub-array
print("\nBasic Slicing (sub-array):", arr[1:3, 1:3])
# Integer indexing to access specific elements
print("\nInteger Indexing (specific element):", arr[0, 2])
# Accessing multiple elements using integer arrays
print("Integer Indexing (multiple elements):", arr[[0, 1, 2], [0, 1, 2]])
# Boolean indexing to extract elements greater than 5
bool_array = arr > 5
print("\nBoolean Indexing (condition mask):")
print(bool_array)
filtered_elements = arr[bool_array]
print("\nFiltered elements (greater than 5):", filtered_elements)
28)
import numpy as np
# Creating an array
arr = np.array([1, 2, 3, 4, 5])
print("Minimum value:", arr.min())
print("Maximum value:", arr.max())
print("Sum of the array:", arr.sum())
print("Cumulative sum of the array:", arr.cumsum())
# Finding the cumulative sum of the array elements
arr2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("\n2D Array:")
print(arr2)
print("Column Sum:", np.sum(arr2, axis=1))
print("Row Sum:", np.sum(arr2, axis=0))
print("Cumulative Sum:", np.cumsum(arr2))
29)
import pandas as pd
data = {
'Name': ['Praveen', 'Ram', 'Roja', 'David', 'Uday', 'Prabhakar', 'Tulasi', 'Swathi', 'Satya', 'Vasu'],
'Age': [25, 30, 22, 35, 28, 40, 32, 45, 29, 26],
'Height': [5.5, 6.0, 5.8, 6.2, 5.6, 5.9, 6.1, 5.7, 6.3, 5.4],
'Weight': [65, 70, 68, 75, 72, 80, 78, 85, 74, 69],
'Score': [85, 90, 88, 95, 80, 92, 87, 93, 89, 86]
}
df = pd.DataFrame(data)
print(df.head())
print("\nSelecting the 'Name' column:")
print(df['Name'])
print("\nSelecting the 'Name' and 'Age' columns:")
print(df[['Name', 'Age']])
print("\nSelecting the first three rows (0, 1, 2):")
print(df.iloc[:3])
print("\nSelecting rows where 'Age' is greater than 30:")
print(df[df['Age'] > 30])
print("\nSelecting rows where 'Age' > 30 and 'Score' > 90:")
print(df[(df['Age'] > 30) & (df['Score'] > 90)])
print("\nSelecting rows 1 and 3 for columns 'Name' and 'Height':")
print(df.loc[[1, 3], ['Name', 'Height']])
30)
import pandas as pd
import matplotlib.pyplot as plt
# Creating a DataFrame from the dictionary
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Heidi', 'Ivan', 'Judy'],
'Age': [23, 30, 35, 40, 22, 28, 32, 36, 29, 25],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio', 'San Diego', 'Dallas', 'Austin'],
'Salary': [70000, 80000, 120000, 110000, 95000, 88000, 91000, 76000, 99000, 85000],
'Department': ['HR', 'IT', 'Finance', 'IT', 'HR', 'Finance', 'IT', 'HR', 'Finance', 'IT']
})
# Creating a scatter plot to observe the relationship between Age and Salary
plt.figure(figsize=(10, 6))
plt.scatter(df['Age'], df['Salary'], color='blue', marker='o')
plt.title('Scatter Plot of Age vs. Salary')
plt.xlabel('Age')
plt.ylabel('Salary')
plt.grid(True)
plt.show()