Python Lab fileVANSH-1
Python Lab fileVANSH-1
PANIPAT INSTITUTE OF
ENGINEERING AND TECHNOLOGY
Department of AI & ML
PYTHON LAB - II
(PC-CS-AIML - 220 A)
Affiliated to:
1|Page
Vansh 2822649
INDEX
2|Page
Vansh 2822649
Program No. 1
Aim: Write a program to implement numpy and scipy library of python.
Program:-
# numpy Library
import numpy as np
Output:
3|Page
Vansh 2822649
#The Basics
import numpy as np
# Print the total number of bytes consumed by the elements of the array
print("\nTotal number of bytes (nbytes):")
print(a.nbytes)
Output:
4|Page
Vansh 2822649
#Append
import numpy as np
Output:
#Reshape
import numpy as np
# Original array
a = np.array([[1, 2, 3], [4, 5, 6]])
Output:
import numpy as np
6|Page
Vansh 2822649
# Creating an array of zeros with shape (2, 3)
e = np.zeros([2, 3])
print("Array 'e' filled with zeros:")
print(e)
Output:
#Arithmetic operations
import numpy as np
a = np.array([[1, 2, 2, 3], [1, 3, 4, 5], [1, 2, 3, 4], [1, 3, 4, 2]])
b = np.array([[2, 2, 2, 3], [2, 3, 4, 5], [2, 2, 3, 4], [2, 3, 4, 2]])
# Arithmetic Operators
add = a + b
sub = a - b
mul = a * b
div = a / b
exp = a ** 2
mod = a % 3
print("\nArithmetic Operators:")
7|Page
Vansh 2822649
print(f"Addition:\n{add}")
print(f"Subtraction:\n{sub}")
print(f"Multiplication:\n{mul}")
print(f"Division:\n{div}")
print(f"Exponentiation:\n{exp}")
print(f"Modulus:\n{mod}")
Output:
#Statistical operations
8|Page
Vansh 2822649
import numpy as np
# 1D Array
a1= np.array([1, 2, 3, 4, 5])
print("Median:", np.median(a1))
print("Minimum:", np.min(a1))
print("Maximum:", np.max(a1))
print("Standard Deviation:", np.std(a1))
print("Variance:", np.var(a1))
print("Sum:", np.sum(a1))
print("Product:", np.prod(a1))
print("Count Nonzero:", np.count_nonzero(a1))
Output:
import numpy as np
# 3D Array
a3 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]])
print("\n3D Array - Statistical Operations by Axis:")
print("Depth-wise Minimum:")
print(np.min(a3, axis=0))
print("Height-wise Minimum:")
print(np.min(a3, axis=1))
print("Width-wise Minimum:")
print(np.min(a3, axis=2))
9|Page
Vansh 2822649
print("Depth-wise Maximum:")
print(np.max(a3, axis=0))
print("Height-wise Maximum:")
print(np.max(a3, axis=1))
print("Width-wise Maximum:")
print(np.max(a3, axis=2))
print("Depth-wise Mean:")
print(np.mean(a3, axis=0))
print("Depth-wise Median:")
print(np.median(a3, axis=0))
print("Cumulative Sum along Depth:")
print(np.cumsum(a3, axis=0))
Output:
10 | P a g e
Vansh 2822649
#Comparison
import numpy as np
11 | P a g e
Vansh 2822649
print(a < 5)
# Check if each element of array 'b' is less than each element of array 'a'
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
print(b < a)
Output:
#Bitwise
#bitwise operation(and)
import numpy as np
a1= np.array([1,3])
a2= np.array([4,5])
a3 = np.bitwise_and(a1, a2)
print ("Bitwise operation(and) =",a3)
#bitwise operation(or)
a1= np.array([5,8])
a2= np.array([9,2])
a3 = np.bitwise_and(a1, a2)
#bitwise operation(XOR)
a1= np.array([5,6])
a2= np.array([9,3])
a3 = np.bitwise_xor(a1, a2)
print ("Bitwise operation(XOR) =" ,a3)
12 | P a g e
Vansh 2822649
a1= np.array([5,8])
a2= np.array([9,2])
a3 = np.left_shift(a1, a2)
print ("Bitwise operation(left shift) =",a3)
Output:
#Copying
import numpy as np
# Deep copy: g is a new array object with a copy of the data from c
g = np.copy(c)
print("c:")
print(c)
print("g (should not be affected):")
print(g)
Output:
#scipy Library
a=np.array([[0,1,1,0,0],[1,2,0,0,0]])
print(csr_matrix(a))
print (csr_matrix(a).data)
print (csr_matrix(a).count_nonzero)
print(csr_matrix(a).eliminate_zeros)
print(csr_matrix(a).sum_duplicates)
Output:
#Root
def eq(x):
return x+np.cos(x)
myroot=root (eq,0)
print(myroot.x)
Output:
#Linear Algebra
import numpy as np
15 | P a g e
Vansh 2822649
a1= np.array([[5,8,3],[2,6,4]])
print(np.transpose(a1))
print(np.trace(a1))
Output:
Program No. 2
Aim: Write a program to implement matplotlib and pandas library of python.
16 | P a g e
Vansh 2822649
Program:-
#Line Graph
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Output:
x1= np.array([0,1,2,])
y1= np.array([3,4,5])
x2= np.array([6,7,8])
y2= np.array([9,10,11])
plt.plot(x1,y1)
plt.plot(x2,y2)
plt.plot(x1,y1,x2,y2)
plt.show()
Output:
17 | P a g e
Vansh 2822649
#zigzag line
xpoints = np.array([2, 4, 8, 10])
ypoints = np.array([2, 4, 2, 4])
plt.plot(xpoints, ypoints)
plt.show()
OUTPUT:
#markers
ypoints = np.array([3, 8, 1, 10])
18 | P a g e
Vansh 2822649
OUTPUT:
OUTPUT:
plt.plot(x, y)
plt.title("alt./temp.")
plt.xlabel("Altitude")
19 | P a g e
Vansh 2822649
plt.ylabel("Temprature")
plt.show()
OUTPUT:
#subplots
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
OUTPUT:
20 | P a g e
Vansh 2822649
Program No. 3
21 | P a g e
Vansh 2822649
Program :-
import pandas as pd
#using dataset
df = pd.read_csv('data.csv')
print(df.sample(10))
Output:
#using series
Output:
#using dataframe
data = {
"student": ["Ram", "Shyam", "Geeta", "Seeta", "Kush", "Khushi", "Dhruv"],
22 | P a g e
Vansh 2822649
df1 = pd.DataFrame(data)
print(df1.sample(3))
Output:
Program No. 4
23 | P a g e
Vansh 2822649
Aim: Write a program to evaluate mean, median and mode of a dataset in
python.
Program :-
import pandas as pd
a = [1, 6, 17, 23, 45, 23, 67, 84, 17, 96]
df = pd.Series(a)
mean = df.mean()
print(“Mean “,mean)
median = df.median()
print(“Median “,median)
mode = df.mode()
print(“Mode “,mode)
Output:
#Using datframes
import pandas as pd
data = {
'Name':['Vansh','Sujal','Sumit','Rounak','Ayush'],
'Age':[20,20,19,20,21],
'Class':['A','B','A','C','D'],
'Marks':[40,39,38,37,39]
}
c = pd.DataFrame(data)
print(c)
Output:
#CSV FILE
import pandas as pd
Output:
25 | P a g e
Vansh 2822649
Program No. 5
Program :-
import numpy as np
import matplotlib.pyplot as plt
num=[1,11,25,56,28,90,72,34]
means=[]
for j in num:
np.random.seed(1)
x=[np.mean(np.random.randint(-40,40,j)) for _i in range (1000)]
means.append(x)
k=0
fig,ax=plt.subplots(2,2,figsize=(8,8))
Output:
26 | P a g e
Vansh 2822649
Program No. 6
import numpy as np
Output:
27 | P a g e
Vansh 2822649
Program No. 7
# Descriptive Statistics
print("Descriptive Statistics:")
print("Mean:")
print(data.mean())
print("\nStandard Deviation:")
print(data.std())
print("\nSummary Statistics:")
print(data.describe())
# Histograms
plt.subplot(2, 2, 1)
plt.hist(data['Height'], bins=10, alpha=0.7, color='blue', edgecolor='black')
plt.title('Height Distribution')
plt.xlabel('Height (cm)')
plt.ylabel('Frequency')
plt.subplot(2, 2, 2)
plt.hist(data['Weight'], bins=10, alpha=0.7, color='green', edgecolor='black')
28 | P a g e
Vansh 2822649
plt.title('Weight Distribution')
plt.xlabel('Weight (kg)')
plt.ylabel('Frequency')
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.grid(True)
plt.show()
Output:
Output:
30 | P a g e
Vansh 2822649
Program No. 8
n=20
p=0.5
r_values=list(range (n+1))
print(r_values)
mean,var=binom.stats(n,p)
print(mean)
print(var)
dist_1=[binom.pmf(r,n,p)for r in r_values]
print("r\tp(r)")
print("mean ="+str(mean))
print("variance ="+str(var))
31 | P a g e
Vansh 2822649
Output:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
N = 400
data = np.random.randn(N)
count,bins_count = np.histogram(data,density=True,bins=10)
print(count)
print(bins_count)
pdf=count/sum(count)
print(pdf)
plt.plot(bins_count[1:],pdf,label="PDF")
plt.legend()
plt.show()
32 | P a g e
Vansh 2822649
Output:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
N = 400
data = np.random.randn(N)
count,bins_count = np.histogram(data,density=True,bins=10)
print(count)
print(bins_count)
pdf=count/sum(count)
cdf=np.cumsum(pdf)
print(cdf)
plt.plot(bins_count[1:],cdf,label="CDF")
plt.legend()
plt.show()
33 | P a g e
Vansh 2822649
Output:
34 | P a g e
Vansh 2822649
Program No. 9
#Bar Graph
import numpy as np
import matplotlib.pyplot as plt
Output:
35 | P a g e
Vansh 2822649
# Histogram
import numpy as np
import matplotlib.pyplot as plt
Output:
36 | P a g e
Vansh 2822649
#Pie Chart
Output:
37 | P a g e
Vansh 2822649
#Scatter Plot
plt.xlabel('Math Scores')
plt.ylabel('Science Scores')
plt.title('Math vs Science Scores')
plt.show()
Output:
38 | P a g e
Vansh 2822649
#Line Plot
plt.xlabel('Months')
plt.ylabel('Number of Students')
plt.title('Growth in Number of Students Enrolled in Python Course')
plt.show()
Output:
39 | P a g e
Vansh 2822649
Program No. 10
ages_mean=np.mean(ages)
print(ages_mean)
tset,pval=ttest_1samp(ages,30)
print("p-value =",pval)
if pval<0.05:
print("we are rejecting null hypothesis")
else:
print("we are accepting the null hypothesis")
Output:
40 | P a g e
Vansh 2822649
sample_mean=110
population_mean=100
population_std=15
population_size=50
alpha=0.05
z_score=(sample_mean-population_mean)/(population_std/np.sqrt(population_size))
print('z-score =',z_score)
p_value=1-stats.norm.cdf(z_score)
print('p-value',p_value)
if p_value<alpha:
print("we are rejecting null hypothesis")
else:
print("we are accepting the null hypothesis")
Output:
41 | P a g e