[Link]
com/
CST 362: PROGRAMMING IN PYTHON
TUTORIAL QUESTIONS
MODULE-V
1. Add two matrix and find the transpose of the result ( university question)
Ans:
def readmatrix(x,r,c):
m
for i in range(r):
co
for j in range(c):
s.
x[i][j]=int(input('enter elements row by row'))
te
import numpy as np
no
r1=int(input('rows of a'))
la
c1=int(input('columns of a'))
ra
r2=int(input('rows of b'))
ke
c2=int(input('columns of b'))
if r1!=r2 or c1!=c2:
print("cant add matrices")
else:
A=[Link]((r1,c1))
print("Enter the elements of A")
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
readmatrix(A,r1,c1)
B=[Link]((r2,c2))
print("Enter the elements of B")
readmatrix(B,r2,c2)
print("Matrix A")
print(A)
m
print("Matrix B")
co
print(B)
C=A+B
s.
te
print("sum")
no
print(C)
la
print("transpose of sum")
ra
print(C.T)
ke
2. Create a dataframe from a list of data and set the index.
ANS:
import pandas as pd
df = [Link](
[[21, 'Amol', 72, 67],[23, 'Lini', 78, 69],[32, 'Kiku', 74, 56],[52, 'Ajit', 54, 76]],
columns=['rollno', 'name', 'physics', 'botony'])
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
print('DataFrame with default index\n', df)
#set column as index
df = df.set_index('rollno')
print('\nDataFrame with column as index\n',df)
3. Write data to an excel file.
m
ANS:
co
import pandas as pd
# create dataframe
s.
te
df_marks = [Link]({'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
no
'physics': [68, 74, 77, 78],
la
'chemistry': [84, 56, 73, 69],
ra
'algebra': [78, 88, 82, 87]})
ke
# create excel writer object
writer = [Link]('[Link]')
# write dataframe to excel
df_marks.to_excel(writer)
# save the excel
[Link]()
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
print('DataFrame is written successfully to Excel File.')
4. Read data from an excel file.
ANS:
# Program to extract a particular row value
import xlrd
m
loc = ("[Link]")
co
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
s.
te
#extracting column names
no
print(sheet.cell_value(0, 0),sheet.cell_value(0, 1),sheet.cell_value(0, 2))
la
for i in range(1,[Link]):
ra
print(sheet.row_values(i))
ke
5. Write Python program to write the data given below to a CSV file.(university
question)
SN Name Country Contribution Year
1 Linus Torvalds Finland Linux Kernel 1991
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
2 Tim Berners-Lee England World Wide Web 1990
3 Guido van Rossum Netherlands Python 1991
Ans:
import pandas as pd
# dictionary of lists
# creating a dataframe from a dictionary
m
df = [Link]([[1,' Linus Torvalds','Finland','Linux Kernel ',1991],
co
[2,'Tim Berners-Lee','England','World Wide Web',1990],
s.
[3,'Guido van Rossum','Netherlands','Python',1991]],
te
columns=['SN','Name','Country','Contribution','Year'])
no
print("data frame with defaut index=",df)
la
df=df.set_index('SN')
ra
print("data frame with SN as index=",df)
ke
print(df)
df.to_csv('[Link]')
6. Create a data frame from the dictionary of lists.
Ans:
import pandas as pd
# dictionary of lists
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
'degree': ["MBA", "BCA", "[Link]", "MBA"],
'score':[90, 40, 80, 98]}
# creating a dataframe from a dictionary
df = [Link](dict)
print(df)
m
co
7. Given a file “[Link]” of automobile data with the fields index, company,
s.
body-style, wheel-base, length, engine-type, num-of-cylinders, horsepower
average-mileage, and price, write Python codes using Pandas to
te
no
1) Clean and Update the CSV file
2) Find the most expensive car company name
la
ra
3) Print all toyota car details
ke
4) Print total cars of all companies
5) Find the highest priced car of all companies
6) Find the average mileage of all companies
7) Sort all cars by Price column ( university question)
Ans:
Reading the data file and showing the first five records
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
[Link](5)
index company body-style wheel-base length engine-type num-of-cylinders horsepower average-mileage price
0 0 alfa-romero convertible 88.6 168.8 dohc four 111 21 13495.0
1 1 alfa-romero convertible 88.6 168.8 dohc four 111 21 16500.0
2 2 alfa-romero hatchback 94.5 171.2 ohcv six 154 19 16500.0
3 3 audi sedan 99.8 176.6 ohc four 102 24 13950.0
m
4 4 audi sedan 99.4 176.6 ohc five 115 18 17450.0
co
#This will show last 7 rows
[Link](7) s.
te
1) Clean and Update the CSV file
no
import pandas as pd
la
df = pd.read_csv("Automobile_data.csv",
ra
na_values={
ke
'price':["?","n.a"],
'stroke':["?","n.a"],
'horsepower':["?","n.a"],
'peak-rpm':["?","n.a"],
'average-mileage':["?","n.a"]})
print (df)
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
df.to_csv("Automobile_data.csv")
2) Find the most expensive car company name
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
df = df [['company','price']][[Link]==df['price'].max()]
m
print(df)
co
3) Print all toyota car details
s.
te
import pandas as pd
no
df = pd.read_csv("Automobile_data.csv")
la
print(df[df['company']=='toyota'])
ra
OR
ke
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
car_Manufacturers = [Link]('company')
toyotaDf = car_Manufacturers.get_group('toyota')
toyotaDf
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
4)Print total cars of all companies
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
[Link]('company')['company'].count()
OR
import pandas as pd
m
df['company'].value_counts()
co
s.
5) Find the highest priced car of all companies
te
import pandas as pd
no
df = pd.read_csv("Automobile_data.csv")
la
[Link]('company')[['company','price']].max()
ra
ke
6) Find the average mileage of all companies
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
[Link]('company')[['company','average-mileage']].mean()
7) Sort all cars by Price column
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
df.sort_values(by=['price', 'horsepower'], ascending=False)[['company','price']]
8. Create a [Link] file containing rollno, name, place and mark of students. Use
this file and do the following
m
a) Read and display the file contents
b) Set rollno as index
co
c) Display name and mark
s.
d) rollno,Name and mark in the order of name
te
e) Display the rollno,name, mark in the descending order of mark
no
f) Find the average mark,median and mode
la
g) Find minimum and maximum marks
ra
ke
h) variance and standard deviation of marks
i) display the histogram of marks
j) remove the place column ( university question)
ANS:
a)
import pandas as pd
10
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
df = pd.read_csv("[Link]")
print(df)
rollno name place mark
0 101 binu ernkulam 45
1 103 ashik alleppey 35
2 102 faisal kollam 48
3 105 biju kotayam 25
m
4 106 anu thrisur 25
co
5 107 padma kylm 25
s.
te
b)Set rollno as index
no
df=df.set_index('rollno')
la
print(df)
ra
name place mark
ke
rollno
101 binu ernkulam 45
103 ashik alleppey 35
102 faisal kollam 48
105 biju kotayam 25
11
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
106 anu thrisur 25
107 padma kylm 25
c)Display name and mark
df=df[['name','mark']]
print(df)
m
name mark
co
binu 45
ashik 35
s.
te
faisal 48
no
biju 25
la
anu 25
ra
padma 25
ke
d) rollno,Name and mark in the order of name
df=df[['name','mark']]
df=df.sort_values('name')
print(df)
name mark
12
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
rollno
106 anu 25
103 ashik 35
105 biju 25
101 binu 45
102 faisal 48
m
107 padma 25
co
e) Display the rollno,name, mark in the descending order of mark
s.
df=df.sort_values(by='mark',ascending=False)
te
print(df)
no
name mark
la
rollno
ra
102 faisal 48
ke
101 binu 45
103 ashik 35
106 anu 25
105 biju 25
107 padma 25
13
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
f) Find the average mark,median and mode
print(df['mark'].mean())
print(df['mark'].median())
print(df['mark'].mode())
33.833333333333336
30.0
m
25
co
g)Find minimum and maximum marks
print(df['mark'].min())
s.
te
print(df['mark'].max())
no
25
la
48
ra
h)variance and standard deviation of marks
ke
print(df['mark'].var())
print(df['mark'].std())
112.16666666666667
10.59087657687817
i) display the histogram of marks
import [Link] as plt
14
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
[Link](df['mark'])
j) remove the place column
[Link](['place'],axis=1,inplace=True)
print(df)
rollno name mark
0 101 binu 45
m
1 103 ashik 35
co
2 102 faisal 48
3 105 biju 25
s.
te
4 106 ann 25
no
5 107 padma 25
la
9. Given the sales information of a company as CSV file with the following fields
ra
month_number, facecream, facewash, toothpaste, bathingsoap, shampoo,
ke
moisturizer, total_units, total_profit. Write Python codes to visualize the data as
follows
1) Toothpaste sales data of each month and show it using a scatter plot.
2) Face cream and face wash product sales data and show it using the bar
chart.
3) Calculate total sale data for last year for each product and show it using a
Pie chart. ( university question)
ANS:
15
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
1)
import pandas as pd
import [Link] as plt
df = pd.read_csv("sales_data.csv")
monthList = df ['month_number'].tolist()
toothPasteSalesData = df ['toothpaste'].tolist()
m
[Link](monthList, toothPasteSalesData, label = 'Tooth paste Sales data')
co
[Link]('Month Number')
[Link]('Number of units Sold')
s.
te
[Link](loc='upper left')
no
[Link](' Tooth paste Sales data')
la
[Link](monthList)
ra
[Link](True, linewidth= 1, linestyle="--")
ke
[Link]()
2)
import pandas as pd
import [Link] as plt
df = pd.read_csv("sales_data.csv")
monthList = df ['month_number'].tolist()
16
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
faceCremSalesData = df ['facecream'].tolist()
faceWashSalesData = df ['facewash'].tolist()
[Link]([a-0.25 for a in monthList], faceCremSalesData, width= 0.25, label =
'Face Cream sales data', align='edge')
[Link]([a+0.25 for a in monthList], faceWashSalesData, width= -0.25, label
= 'Face Wash sales data', align='edge')
m
[Link]('Month Number')
co
[Link]('Sales units in number')
[Link](loc='upper left')
s.
te
no
[Link](' Sales data')
la
ra
[Link](monthList)
ke
[Link](True, linewidth= 1, linestyle="--")
[Link]('Facewash and facecream sales data')
[Link]()
3)
import pandas as pd
import [Link] as plt
17
For More Study Materials : [Link]
[Link]
CST 362: PROGRAMMING IN PYTHON
df = pd.read_csv("sales_data.csv")
monthList = df ['month_number'].tolist()
labels = ['FaceCream', 'FaseWash', 'ToothPaste', 'Bathing soap', 'Shampoo',
'Moisturizer']
salesData = [df ['facecream'].sum(), df ['facewash'].sum(), df
['toothpaste'].sum(), df ['bathingsoap'].sum(), df ['shampoo'].sum(), df
m
['moisturizer'].sum()]
co
[Link]("equal")
s.
[Link](salesData, labels=labels, autopct='%1.1f%%')
te
[Link](loc='lower right')
no
[Link]('Sales data')
la
[Link]()
ra
ke
18
For More Study Materials : [Link]