Tutorials

Sample Practical File Python Codes XII IP

 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))

OUTPUT:


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))




CODE 5:
Write a NumPy program to create a null vectorof size 10 and update sixth value to 11.
Solution:
import numpy as np
x=np.zeros(10)
print("Acutal Array")
print(x)
print("Updated sixth value to 11")
x[6] = 11
print(x)

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)

OUTPUT:


CODE 8:
Write the NumPy code to create a Matrix of 3x3 with the elements between 0 and 9. Check for even numbers in the matrix and replace them with a random number between 10 and 20.

SOLUTION:
import numpy as np
matrix = np.arange(3,12).reshape(3,3)
print("3 x 3 Matrix is: ")
print(matrix)
a = np.where((matrix%2)==0)
for i in a: 
      matrix[a]=np.random.randint(low=10,high=20)
print("Matrix after replacing even number")
print(matrix)

OUTPUT:



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:




CODE 11:
Write a code to plot a bar chart to depict the pass percentage of students in CBSE exams for the years 2015 to 2018 as shown below

SOLUTION:

import matplotlib.pyplot as plt
import numpy as np
years=('2015','2016','2017','2018')
ypos=np.arange(len(years))
percentage=[80,83,87,92]
plt.bar(ypos,percentage,align="center",color="Orange",width=.5)
plt.xticks(ypos,years)
plt.ylabel("Percentage")
plt.xlabel("Years")
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'])

print("DataFrame 1: ")
print(df1)
print("DataFrame 2: ")
print(df2)
df = df1.append(df2)
print("Combine DataFrame: ")
print(df)
print("Drop rows with index 0")
df = df.drop(0)
print(df)

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:








CODE 16:
Create a DataFrame of students with the following data: Name, Age and Marks. Also perform the aggregate function on the same data.

SOLUTION:

import numpy as np
import pandas as pd
dataframe={'Name':['Jatinder','Santa','Banta','Sandy','Mandy','John'],'Age':[22,24,23,25,22,25],'Marks':[89,86,88,84,87,89]}
marksdf=pd.DataFrame(dataframe,columns=['Name','Age','Marks'])
print('Details of the students are:')
print(marksdf)
print('List of all the column names and its maximum value')
print(marksdf.max())
print('List of all the column names and its minimum value')
print(marksdf.min())
print('Minimum age of the students')
print(marksdf['Age'].min())
print('Total of all the marks')
print(marksdf.sum())
print('Count the No. of students')
print(marksdf['Name'].count())
print("Total number of records")
print(marksdf.count(axis=1))
print("Mean of score and Age")
print(marksdf.mean(axis=0))
print("Median of score and Age")
print(marksdf.median())

OUTPUT:





CODE 17:

Write a code to create a dataframe with the following columns Name, Age, Weight, Height and runs scored. Also display the maximum age amongst each age group.

SOLUTION:

import pandas as pd
import numpy as np
scorecard={'Name':['Jatinder','Santa','Banta','Sandy','Mandy','John','Mohan'],
           'Age':[22,23,21,23,22,23,22],
           'Weight':[40,41,42,40,41,42,41],
           'Height':[5.9,5.4,5.5,5.2,5.1,5.2,5.3],
           'Runsscored':[100,78,45,67,50,55,78]}
dataframe = pd.DataFrame(scorecard)
print("\n")
print("Details of all the Players is:")
print(dataframe)
print("\n")
print("Grouping and then finding the maximum value for in each age group ")
print(dataframe.groupby('Age').max())

OUTPUT:


CODE 18:

Write a code to show index and reindex in dataframe

SOLUTION:

import pandas as pd
import numpy as np
arr = np.array([23,24,25,55,44,33])
series=pd.Series(arr,index=['a','b','c','d','e','f'])
print("Original index series")
print(series)
series1=series.reindex(['f','e','d','c','b','a'])
print("Data after reindexing")
print(series1)

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 comment:

  1. 1)num1=int(input("enter the number1"))
    num2=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)

    ReplyDelete