1 . How to create a one-dimensional NumPy array?
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print("1D NumPy Array: ",arr)
Output:
1D NumPy Array: [1 2 3 4 5]
2 . How to create a two-dimensional NumPy array?
import numpy as np
arr2d = [Link]([[2, 3, 6], [7, 8, 9]])
print("2D NumPy Array:\n",arr2d)
Output:
2D NumPy Array:
[[2 3 6]
[7 8 9]]
3 . How to check the dimension of a NumPy ndarray?
import numpy as np
arr = [Link]([[5, 6, 7], [8, 9, 10]])
print("Number of dimensions:",[Link])
Output:
Number of dimensions: 2
Shiv Shukla
Btech AIML 4th Sem
4 . How to check the type of an ndarray?
import numpy as np
arr = [Link]([1, 2, 3])
print([Link])
Output:
int64
5 . How to check the size of a NumPy array?
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 11, 21])
print("Size of array:",[Link])
Output:
Size of array: 10
6 . How to check the shape of and array?
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print("Shape of array:",[Link])
Output:
Shape of array: (2, 3)
Shiv Shukla
Btech AIML 4th Sem
7 . How to check the data type of a NumPy ndarray?
import numpy as np
arr = [Link]([1, 2, 3])
print("Data type of elements:",[Link])
Output:
Data type of elements: int64
8 . How to create matrices using NumPy functions?
import numpy as np
identity_matrix = [Link](3)
ones_matrix = [Link]((3, 3))
zeros_matrix = [Link]((3, 3))
print("IdentityMatrix:\n",identity_matrix)
print("\nOnes Matrix:\n",ones_matrix)
print("\nZeroesMatrix:\n",zeros_matrix)
Output:
IdentityMatrix:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Ones Matrix:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
ZeroesMatrix:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Shiv Shukla
Btech AIML 4th Sem
9 . How to create a NumPy 1D array using arange()
function?
import numpy as np
arr = [Link](13)
print("Array using arange():",arr)
Output:
Array using arange(): [ 0 1 2 3 4 5 6 7 8 9 10 11 12]
10 . How to create NumPy 1D array using linspace()
function?
import numpy as np
arr = [Link](0, 1, 5)
print("Array using linspace():",arr)
Output:
Array using linspace(): [0. 0.25 0.5 0.75 1. ]
Shiv Shukla
Btech AIML 4th Sem
11 . How to convert a 1D array to a multidimensional array
using reshape()?
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
arr_reshaped = [Link](2, 3)
print("Reshaped Array:\n",arr_reshaped)
Output:
Reshaped Array:
[[1 2 3]
[4 5 6]]
12 . How to convert a multidimensional array into a one
dimensional array?
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
arr_flattened = [Link]()
print("Flattened Array:",arr_flattened)
Output:
Flattened Array: [1 2 3 4 5 6]
Shiv Shukla
Btech AIML 4th Sem
13 . Create two arrays using [Link]() and reshape
them into 2D using [Link]() functions.
import numpy as np
arr1 = [Link](6).reshape(2, 3)
arr2 = [Link](6, 12).reshape(2, 3)
print("Array 1:\n",arr1)
print("Array 2:\n",arr2)
Output:
Array 1:
[[0 1 2]
[3 4 5]]
Array 2:
[[ 6 7 8]
[ 9 10 11]]
14 . Write a program to add two NumPy arrays.
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
newarr = arr1 + arr2
print(newarr)
Output:
[5 7 9]
Shiv Shukla
Btech AIML 4th Sem
15 . Write a program to subtract two NumPy arrays.
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
newarr = arr1 - arr2
print(newarr)
Output:
[-3 -3 -3]
16 . Write a program to divide two NumPy arrays.
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
newarr = arr1 / arr2
print(newarr)
Output:
[0.25 0.4 0.5 ]
Shiv Shukla
Btech AIML 4th Sem
17 . Write a program to multiply two NumPy arrays
(element – wise).
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
newarr = arr1 * arr2
print(newarr)
Output:
[ 4 10 18]
18 . Write a program for Matrix Product of two NumPy
arrays(matrix multiplication).
import numpy as np
a = [Link]([[1, 2], [3, 4]])
b = [Link]([[5, 6], [7, 8]])
c = [Link](a, b)
print(c)
Output:
[[19 22]
[43 50]]
Shiv Shukla
Btech AIML 4th Sem
19 . Write a program using NumPy mathematical built-in
functions.
import numpy as np
a = [Link]([1, 4, 9, 16])
print([Link](a))
print([Link](a))
print([Link](a))
print([Link](a))
print([Link](a))
Output:
[1. 2. 3. 4.]
[2.71828183e+00 5.45981500e+01 8.10308393e+03
8.88611052e+06]
[0. 1.38629436 2.19722458 2.77258872]
[ 0.84147098 -0.7568025 0.41211849 -0.28790332]
[ 0.54030231 -0.65364362 -0.91113026 -0.95765948]
Shiv Shukla
Btech AIML 4th Sem
20 . Write a program using NumPy trigonometric
functions.
import numpy as np
a = [Link]([0, [Link]/6, [Link]/4, [Link]/2])
print([Link](a))
print([Link](a))
print([Link](a))
print([Link]([Link](a)))
print([Link]([Link](a)))
print([Link]([Link](a)))
Output:
[0. 0.5 0.70710678 1. ]
[1.00000000e+00 8.66025404e-01 7.07106781e-01 6.12323400e-17]
[0.00000000e+00 5.77350269e-01 1.00000000e+00
1.63312394e+16]
[0. 0.52359878 0.78539816 1.57079633]
[0. 0.52359878 0.78539816 1.57079633]
[0. 0.52359878 0.78539816 1.57079633]
Shiv Shukla
Btech AIML 4th Sem
21 . Write a program to show graphical representation of
the trigonometric sine function.
import numpy as np
import [Link] as plt
x = [Link](0, 2*[Link], 100)
y = [Link](x)
[Link](x, y)
[Link]("x")
[Link]("sin(x)")
[Link]("Sine Function")
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
22 . Write a program to show graphical representation of
the trigonometric cosine function.
import numpy as np
import [Link] as plt
x = [Link](0, 2*[Link], 100)
y = [Link](x)
[Link](x, y)
[Link]("x")
[Link]("cos(x)")
[Link]("Cosine Function")
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
23 . Write a program to show graphical representation of
the trigonometric tangent function.
import numpy as np
import [Link] as plt
x = [Link](-2*[Link], 2*[Link], 1000)
y = [Link](x)
[Link](x, y)
[Link]("x")
[Link]("tan(x)")
[Link]("Tangent Function")
[Link](-10, 10)
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
24 . Write a program using the random module and its
different functions.
import numpy as np
print([Link]())
print([Link](1, 10))
print([Link](3))
print([Link]([10, 20, 30, 40]))
print([Link]([Link]([1, 2, 3, 4])))
Output:
0.4039462449776142
4
[-0.49191662 1.65547917 0.42687982]
40
None
Shiv Shukla
Btech AIML 4th Sem
25 . Write a program to show different NumPy string
operations.
import numpy as np
a = [Link](['hello', 'world'])
print([Link](a))
print([Link](a))
print([Link](a))
print([Link](a))
print([Link](a))
print([Link]('-', a))
Output:
['HELLO' 'WORLD']
['hello' 'world']
['Hello' 'World']
['Hello' 'World']
[list(['hello']) list(['world'])]
['h-e-l-l-o' 'w-o-r-l-d']
Shiv Shukla
Btech AIML 4th Sem
26 . Write a program to show different methods of
creating a series.
import pandas as pd
import numpy as np
s1 = [Link]([1, 2, 3, 4])
s2 = [Link]([Link]([5, 6, 7, 8]))
s3 = [Link]({'a': 10, 'b': 20, 'c': 30})
s4 = [Link](100, index=[0, 1, 2, 3])
print(s1)
print(s2)
print(s3)
print(s4)
Output:
0 1
1 2
2 3
3 4
dtype: int64
0 5
1 6
2 7
3 8
dtype: int64
a 10
b 20
c 30
dtype: int64
0 100
1 100
2 100
3 100
dtype: int64
Shiv Shukla
Btech AIML 4th Sem
27 . Write a program to create different data frames with
different ways.
import pandas as pd
import numpy as np
df1 = [Link]({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = [Link]([Link]([[1, 2], [3, 4], [5, 6]]), columns=['A', 'B'])
df3 = [Link]([{'A': 1, 'B': 2}, {'A': 3, 'B': 4}])
df4 = [Link](list(zip([1, 2, 3], [4, 5, 6])), columns=['A', 'B'])
print(df1)
print(df2)
print(df3)
print(df4)
Output:
A B
0 1 4
1 2 5
2 3 6
A B
0 1 2
1 3 4
2 5 6
A B
0 1 2
1 3 4
A B
0 1 4
1 2 5
2 3 6
Shiv Shukla
Btech AIML 4th Sem
28 . How to Read or Import CSV file in Python IDLE?
import csv
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
Output:
['', 'Name', 'Marks', 'City']
['0', 'Harry', '34', 'Rampur']
['1', 'Rohan', '56', 'Kolkata']
['2', 'Skillf', '24', 'Barely']
['3', 'Scent', '98', 'Antarctica']
Shiv Shukla
Btech AIML 4th Sem
29 . How to write CSV file in Python?
import csv
data = [
['Name', 'Age', 'City'],
['Steven', 25, 'Delhi'],
['Noah', 30, 'Mumbai']
]
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](data)
Output:
Name,Age,City
Steven,25,Delhi
Noah,30,Mumbai
Shiv Shukla
Btech AIML 4th Sem
30 . Write a program to handle missing values in Python.
import pandas as pd
import numpy as np
data = [Link]({
'A': [1, 2, [Link], 4],
'B': [5, [Link], 7, 8],
'C': [[Link], 10, 11, 12]
})
print([Link]())
print([Link]())
print([Link](0))
print([Link]([Link](numeric_only=True)))
Output:
A B C
0 False False True
1 False True False
2 True False False
3 False False False
A B C
3 4.0 8.0 12.0
A B C
0 1.0 5.0 0.0
1 2.0 0.0 10.0
2 0.0 7.0 11.0
3 4.0 8.0 12.0
A B C
0 1.000000 5.000000 11.0
1 2.000000 6.666667 10.0
2 2.333333 7.000000 11.0
3 4.000000 8.000000 12.0
Shiv Shukla
Btech AIML 4th Sem
31 . Write a program by using GroupBy function in Python.
import pandas as pd
data = [Link]({
'Department': ['HR', 'IT', 'HR', 'IT', 'Finance'],
'Employee': ['A', 'B', 'C', 'D', 'E'],
'Salary': [30000, 50000, 35000, 60000, 40000]
})
grouped = [Link]('Department')
print([Link](numeric_only=True))
print([Link](numeric_only=True))
print([Link]())
Output:
Salary
Department
Finance 40000
HR 65000
IT 110000
Salary
Department
Finance 40000.0
HR 32500.0
IT 55000.0
Employee Salary
Department
Finance E 40000
HR C 35000
IT D 60000
Shiv Shukla
Btech AIML 4th Sem
32 . Write a program by using concate() in Python.
import pandas as pd
df1 = [Link]({'A': [1, 2], 'B': [3, 4]})
df2 = [Link]({'A': [5, 6], 'B': [7, 8]})
result = [Link]([df1, df2])
print(result)
Output:
A B
0 1 3
1 2 4
0 5 7
1 6 8
33 . Write a program by using Join() in Python?
import pandas as pd
df1 = [Link]({'A': [1, 2, 3]}, index=['a', 'b', 'c'])
df2 = [Link]({'B': [4, 5, 6]}, index=['a', 'b', 'c'])
result = [Link](df2)
print(result)
Output:
A B
a 1 4
b 2 5
c 3 6
Shiv Shukla
Btech AIML 4th Sem
34 . Write a program by using Append() in Python.
import pandas as pd
df1 = [Link]({'A': [1, 2], 'B': [3, 4]})
df2 = [Link]({'A': [5, 6], 'B': [7, 8]})
result = df1._append(df2)
print(result)
Output:
A B
0 1 3
1 2 4
0 5 7
1 6 8
Shiv Shukla
Btech AIML 4th Sem
35 . Write a program to Draw Multiple Line Plot by using
Seaborn library.
import seaborn as sns
import pandas as pd
import [Link] as plt
data = [Link]({
'x': [1, 2, 3, 4, 5],
'y1': [2, 3, 5, 7, 11],
'y2': [1, 4, 6, 8, 10]
})
[Link](data['x'], data['y1'])
[Link](data['x'], data['y2'])
[Link]("X")
[Link]("Y")
[Link]("Multiple Line Plot")
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
36 . Write a program to draw a matplotlib line plot with
different style and format.
import [Link] as plt
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
[Link](x, y1, linestyle='--', marker='o')
[Link](x, y2, linestyle='-.', marker='s')
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Line Plot with Different Styles")
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
37 . Write a program to show different types of OOPS
operation in python?
class Person:
def __init__(self, name):
[Link] = name
def display(self):
print([Link])
class Student(Person):
def __init__(self, name, marks):
super().__init__(name)
[Link] = marks
def display(self):
print([Link], [Link])
class Teacher(Person):
def __init__(self, name, subject):
super().__init__(name)
[Link] = subject
def display(self):
print([Link], [Link])
p = Person("Nathan")
s = Student("Sara", 90)
t = Teacher("Charlie", "Math")
[Link]()
[Link]()
[Link]()
Output:
Nathan
Sara 90
Charlie Math
Shiv Shukla
Btech AIML 4th Sem
38 . How to store different types of data in NumPy
ndarray?
import numpy as np
arr = [Link]([1, 'hello', 3.14, True], dtype=object)
print(arr)
print([Link])
Output:
[1 'hello' 3.14 True]
object
39 . How do you convert Pandas DataFrame to a NumPy
array?
import pandas as pd
df = [Link]({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
arr = df.to_numpy()
print(arr)
Output:
[[1 4]
[2 5]
[3 6]]
Shiv Shukla
Btech AIML 4th Sem
40 . Write a program to show different types of operator in
python.
# Arithmetic Operators
a = 10
b=3
print("Arithmetic Operators:")
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", a % b)
print("a ** b =", a ** b)
print("a // b =", a // b)
# Comparison Operators
print("\nComparison Operators:")
print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
# Logical Operators
x = True
y = False
print("\nLogical Operators:")
print("x and y:", x and y)
print("x or y:", x or y)
print("not x:", not x)
# Assignment Operators
c=5
print("\nAssignment Operators:")
c += 2
print("c += 2:", c)
c -= 1
print("c -= 1:", c)
c *= 3
print("c *= 3:", c)
Output:
Shiv Shukla
Btech AIML 4th Sem
Arithmetic Operators:
a + b = 13
a-b=7
a * b = 30
a / b = 3.3333333333333335
a%b=1
a ** b = 1000
a // b = 3
Comparison Operators:
a == b: False
a != b: True
a > b: True
a < b: False
Logical Operators:
x and y: False
x or y: True
not x: False
Assignment Operators:
c += 2: 7
c -= 1: 6
c *= 3: 18
Shiv Shukla
Btech AIML 4th Sem
41 . Write a program to show different types of control
structure in python.
# Selection Control Structure (if, if-else, if-elif-else)
num = 10
print("Selection Statements:")
if num > 0:
print("Number is positive")
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
# Iteration Control Structure (loops)
print("\nIteration Statements:")
print("For loop:")
for i in range(1, 6):
print(i, end=" ")
print("\nWhile loop:")
i=1
while i <= 5:
print(i, end=" ")
i += 1
# Jump Control Structure (break, continue, pass)
print("\n\nJump Statements:")
print("Break example:")
for i in range(1, 6):
if i == 3:
break
print(i, end=" ")
print("\nContinue example:")
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ")
print("\nPass example:")
for i in range(1, 4):
if i == 2:
pass
Shiv Shukla
Btech AIML 4th Sem
print(i, end=" ")
Output:
Selection Statements:
Number is positive
Even number
Iteration Statements:
For loop:
12345
While loop:
12345
Jump Statements:
Break example:
12
Continue example:
1245
Pass example:
123
Shiv Shukla
Btech AIML 4th Sem
42 . Write a program to show different types of string
manipulation in python.
text = "Hello World"
print("Original String:", text)
# 1. Changing case
print("\nCase Conversion:")
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
# 2. String concatenation
str1 = "Hello"
str2 = "Python"
print("\nConcatenation:")
print(str1 + " " + str2)
# 3. String repetition
print("\nRepetition:")
print(str1 * 3)
# 4. Indexing and slicing
print("\nIndexing and Slicing:")
print("Substring (0:5):", text[0:5])
# 5. String length
print("\nLength of string:")
print(len(text))
# 6. Searching in string
print("\nSearching:")
print("Find 'World':", [Link]("World"))
print("Count of 'l':", [Link]("l"))
Output:
Shiv Shukla
Btech AIML 4th Sem
Original String: Hello World
Case Conversion:
Uppercase: HELLO WORLD
Lowercase: hello world
Concatenation:
Hello Python
Repetition:
HelloHelloHello
Indexing and Slicing:
Substring (0:5): Hello
Length of string:
11
Searching:
Find 'World': 6
Count of 'l': 3
Shiv Shukla
Btech AIML 4th Sem
43 . Implementation of simple regression model for real
life problem.
import numpy as np
from sklearn.linear_model import LinearRegression
import [Link] as plt
area = [Link]([500, 700, 900, 1100, 1300]).reshape(-1, 1)
price = [Link]([100, 150, 200, 250, 300])
model = LinearRegression()
[Link](area, price)
predicted_price = [Link](area)
[Link](area, price)
[Link](area, predicted_price)
[Link]("Area")
[Link]("Price")
[Link]("Linear Regression Model")
[Link]()
new_area = [Link]([[1000]])
print([Link](new_area))
Output:
Shiv Shukla
Btech AIML 4th Sem
44 . Implementation of logistic regression model for real
life problem.
import numpy as np
from sklearn.linear_model import LogisticRegression
import [Link] as plt
hours = [Link]([1, 2, 3, 4, 5, 6]).reshape(-1, 1)
result = [Link]([0, 0, 0, 1, 1, 1])
model = LogisticRegression()
[Link](hours, result)
predicted = [Link](hours)
[Link](hours, result)
[Link](hours, model.predict_proba(hours)[:,1])
[Link]("Study Hours")
[Link]("Probability of Passing")
[Link]("Logistic Regression Model")
[Link]()
new_hours = [Link]([[3.5]])
print([Link](new_hours))
Output:
Shiv Shukla
Btech AIML 4th Sem
45 . Develop a model for K-means algorithm.
import numpy as np
from [Link] import KMeans
import [Link] as plt
data = [Link]([
[15, 39], [16, 81], [17, 6], [18, 77], [19, 40],
[20, 76], [21, 6], [22, 94], [23, 3], [24, 72]
])
kmeans = KMeans(n_clusters=3)
[Link](data)
labels = kmeans.labels_
centers = kmeans.cluster_centers_
[Link](data[:, 0], data[:, 1], c=labels)
[Link](centers[:, 0], centers[:, 1], marker='X')
[Link]("Income")
[Link]("Spending Score")
[Link]("K-Means Clustering")
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
46 . Develop a model for K-nearest algorithm.
import numpy as np
from [Link] import KNeighborsClassifier
import [Link] as plt
data = [Link]([
[22, 20000], [25, 25000], [47, 50000], [52, 60000],
[46, 55000], [56, 65000], [28, 30000], [30, 35000]
])
labels = [Link]([0, 0, 1, 1, 1, 1, 0, 0])
model = KNeighborsClassifier(n_neighbors=3)
[Link](data, labels)
predicted = [Link](data)
[Link](data[:, 0], data[:, 1], c=labels)
[Link]("Age")
[Link]("Salary")
[Link]("KNN Classification")
[Link]()
new_person = [Link]([[40, 40000]])
print([Link](new_person))
Output:
Shiv Shukla
Btech AIML 4th Sem
47 . Study and plotting of confusion matrix.
import numpy as np
import [Link] as plt
import seaborn as sns
from [Link] import confusion_matrix
y_true = [0, 1, 0, 1, 0, 1, 1, 0]
y_pred = [0, 1, 0, 0, 0, 1, 1, 1]
cm = confusion_matrix(y_true, y_pred)
print(cm)
[Link](cm, annot=True, fmt='d')
[Link]("Predicted")
[Link]("Actual")
[Link]("Confusion Matrix")
[Link]()
Output:
Shiv Shukla
Btech AIML 4th Sem
Shiv Shukla
Btech AIML 4th Sem