NumPy Codes
CODE 1:
Write a NumPy program to create an arrary of 10 zeros , 10 ones and 10 fives.
Solution:
import numpy as np
array0 = np.zeros(10)
print("An Array of 10 Zeros : ")
print (array0)
array1 = np.ones(10)
print("An Array of 10 Ones : ")
print (array1)
array5 = np.ones(10)*5
print("An Array of 10 Fives : ")
print (array5)
OUTPUT:
CODE 2:
Write a NumPy program to test whether none of the elements of a given array is zero.
Solution:
import numpy as np
x = np.array([1,2,3,4])
print("Original Array: ")
print(x)
print("Test if none of the elements of the said array is zero")
print(np.all(x))
x = np.array([0,1,2,3])
print("Original Array: ")
print(x)
print("Test if none of the elements of the said array is zero")
print(np.all(x))
CODE 3:
Write a NumPy program to find the number of rows and columns of the given matrix.
Example:
Matrix:
[[10,11,12,13],
[14,15,16,17],
[18,19,20,21]]
Number of rows and columns of the given matrix is 3(rows) and 4(columns)
Solution:
import numpy as np
n = np.arange(10,22).reshape([3,4])
print("Matrix: ")
print(n)
print("Number of rows and columns of the given matrix: ")
print(n.shape)
OUTPUT:
CODE 4:
Write a NumPy program to compute sum of all elements, sum of each column and sum of each row of a given array.
Example:
Original Array:
[[0,1]
[2,3]]
Sum of all elements: 6
Sum of each ROW: [2 4]
Sum of each COLUMN:[1 5]
Solution:
import numpy as np
x = np.array([0,1],[2,3]])
print("Actual Array: ")
print(x)
print("Sum of all elements: ",np.sum(x))
print("Sum of each Column: ",np.sum(x,axis=0))
print("Sum of each Column: ",np.sum(x,axis=1))
OUTPUT:
CODE 6:
Write a NumPy program to create a 3x3 Matrix with values ranging from 2 to 10.
SOLUTION:
import numpy as np
x = np.arange(2,11).reshape(3,3)
print("Matrix of 3 x 3 is : ")
print(x)
OUTPUT:
CODE 7:
Write a code in python to replace all 0 values with any random numbers. The matrix size is 3 x 3.
SOLUTION:
import numpy as np
arr1=np.identity(3)
print("Array of 3 x 3 with diagonal as 1:")
print(arr1)
x=np.where(arr1==0)
for i in x: # 3 times
arr1[x]=np.random.randint(low=10,high=20)
print()
print("Array of 3 x 3 with diagonal as 1 and 0 replaced with random numbers:")
print(arr1)
CODE 8:
Data Visualization Using PyPlot
CODE 9:
Write a code in python to create a bar graph for the following data
Student Name: Jatinder, Santa, Banta, John, Jonny
Maths Marks: 60,70,80,20,40
The Bar graph should have all the graph elements like legend, grid, xlabel, ylabel and title
SOLUTION:
import numpy as np
import matplotlib.pyplot as plt
name=np.array(["Jatinder","Santa","Banta","John","Jonny"])
mathsmarks=np.array([60,70,80,20,40])
plt.bar(name,mathsmarks,label="Maths Marks")
plt.grid()
plt.legend()
plt.xlabel("Student Names")
plt.ylabel("Marks")
plt.title("Maths Marks Details")
plt.show()
OUTPUT:
CODE 10:
Write a program to plot an algebraic expression: 10x + 14 using the chart.
SOLUTION:
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(12,20)
y = 10 * x + 14
plt.title("Graph for an Algebraic Expression: 10x + 14")
plt.xlabel("X Axis")
plt.ylabel("Y Label")
plt.plot(x,y)
plt.show()
OUTPUT:
Python Pandas
CODE 12:
Write a program to create a dataframe and then use the drop command to drop the data in dataframe.
SOLUTION:
import pandas as pd
df1=pd.DataFrame([[1,2],[3,4]], columns=['a','b'])
df2=pd.DataFrame([[5,6],[7,8]], columns=['a','b'])
OUTPUT:
CODE 13:
Given the dataset for employee
data=['Rajiv',28,'Accountant'],['Sameer',34,'Cashier'],['Ramesh',33,'Clerk'],['Jatinder',42,'Manager']
Write a program to convert this dataset into dataframe and then perform pivoting on the dataframe. Also draw a histogram on the basis of employee data.
SOLUTION:
import pandas as pd
import matplotlib.pyplot as plt
data=[['Rajiv',28,'Accountant'],['Sameer',34,'Cashier'],['Ramesh',33,'Clerk'],['Jatinder',42,'Manager']]
df = pd.DataFrame(data,columns=['Name','Age','Designation'])
print(df)
data1={'Name':['Rajiv','Sameer','Ramesh','Jatinder'],'Age':[28,34,34,42]}
df1 = pd.DataFrame(data1)
print(df1)
pd.pviot_table(df,index=['Name'],values=['Age']).hist()
plt.show()
OUTPUT:
CODE 14:
Create a dataframe for students and then sort the data based on marks in ascending order and descending order.
SOLUTION:
import pandas as pd
studentmarks=pd.Series({'Jatinder':80,'Santa':78,'Banta':70,'Sandy':88,'Mandy':90})
studentage=pd.Series({'Jatinder':20,'Santa':21,'Banta':23,'Sandy':22,'Mandy':20})
studentdataframe=pd.DataFrame({'Marks':studentmarks,"StudentAge":studentage})
print("Student Details")
print(studentdataframe)
print("Marks in Ascending Order(using Sorting)")
print(studentdataframe.sort_values(by=['Marks']))
print("Marks in Descending Order(using Sorting)")
print(studentdataframe.sort_values(by=['Marks'],ascending=False))
OUTPUT:
CODE 15:
Write the code to combine 2 data frames on axis 0 and axis 1
import pandas as pd
data1 = {'rollno':[1,2,3,4,5,6],'sname':['Jatinder','Santa','Banta','Sandy','Mandy','John']}
data2 = {'rollno':[7,8,9,10,11,12],'sname':['inder','San','Ban','andy','Mohan','Heer']}
dataframe1=pd.DataFrame(data1,columns=['rollno','sname'])
print("DataFrame1")
print(dataframe1)
dataframe2=pd.DataFrame(data2,columns=['rollno','sname'])
print("DataFrame2")
print(dataframe2)
print('Combining 2 Data Frame with axis 0 ')
print(pd.concat([dataframe1,dataframe2],axis=0))
print('Combining 2 Data Frame with axis 1 ')
print(pd.concat([dataframe1,dataframe2],axis=1))
OUTPUT:
OUTPUT:
CODE 19:
Q1. Create the following dictionary and run the following commands
grade={'Name':['Jatinder','Santa','Banta','Sandy','Mandy','John','Mohan'],
'Grade':['A1','B2','B1','A2','B1','A2','A1']}
Q2. Output of grade.iloc[0:5] and grade[0:5]
Q3. Add a column called percentage with the following data [92,89,none,95,68,none,93]
Q4. Rearrange the columns as Name, Percentage, Grade
Q5. Drop the column (i.e Grade) by name")
Q6. Delete the 3 and 5 rows
Q7. Output of copyofdataframe.drop(0,axis=0)
Q8. Output of copyofdataframe.drop(0,axis='index')
Q9. Output of copyofdataframe.drop([0,1,2,3],axis=0)
SOLUTION:
import pandas as pd
import numpy as np
grade={'Name':['Jatinder','Santa','Banta','Sandy','Mandy','John','Mohan'],
'Grade':['A1','B2','B1','A2','B1','A2','A1']}
dataframe = pd.DataFrame(grade)
print("\n")
print("Details of all the Students with Grade is:")
print(dataframe)
print("\n")
print("Output of grade.iloc[0:5] and grade[0:5]")
print(dataframe.iloc[0:5])
print(dataframe[0:5])
print("Add a column called percentage with the following data")
print("[92,89,none,95,68,none,93]")
dataframe["Percentage"]=[92,89,None,95,68,None,93]
print(dataframe)
copyofdataframe=dataframe
print("Rearrange the columns as Name, Percentage, Grade")
dataframe=dataframe[['Name','Percentage','Grade']]
print(dataframe)
print("Drop the column (i.e Grade) by name")
dataframe=dataframe.drop('Grade',axis=1)
print(dataframe)
print("Delete the 3 and 5 rows")
dataframe=dataframe.drop([2,4])
print(dataframe)
print("Output of copyofdataframe.drop(0,axis=0)")
print(copyofdataframe.drop(0,axis=0))
print(copyofdataframe)
print("Output of copyofdataframe.drop(0,axis='index')")
print(copyofdataframe.drop(0,axis="index"))
print(copyofdataframe)
print("Output of copyofdataframe.drop([0,1,2,3],axis=0)")
print(copyofdataframe.drop([0,1,2,3],axis=0))
OUTPUT:
CODE 20:
Create Series and then rename the index values
SOLUTIONS:
import pandas as pd
import numpy as np
data=np.array([54,76,88,99,34])
series1=pd.Series(data,index=['a','b','c','d','e'])
print("Series 1:")
print(series1)
series2=series1.rename(index={'a':0,'b':1})
print("Series 2:")
print(series2)
OUTPUT:

1)num1=int(input("enter the number1"))
ReplyDeletenum2=int(input("enter the number2"))
sum=num1+num2
print(sum)
2)eng=int(input("enter the marks of english"))
math=int(input("enter the marks of math"))
phy=int(input("enter the marks of physics"))
chem=int(input("enter the marks of chemistry"))
bio=int(input("enter the marks in biology"))
avg=(eng+math+phy+chem+bio)/5
print(avg)
3)BasicSalary=float(input("enter the salary of Ram"))
HRA=50/100*BasicSalary
DA=20/100*BasicSalary
grosalary=BasicSalary+HRA+DA
print(grosalary)
4)n=int(input("enter any 4-digit number"))
while(n>0):
sum=sum+(n%10)
n=n//10
print(sum)
5)a=int(input("enter first number"))
b=int(input("enter second number"))
c=a
a=b
b=c
print(a)
print(b)
6)a=int(input("enter first number"))
b=int(input("enter second number"))
a=a+b
b=a-b
a=a-b
print(a)
print(b)
7)str1=input("enter any string")
print(str1.upper())
8)num=int(input("enter any number"))
power=int(input("enter the power to be raised"))
res=num**power
print(res)