Practical Assignment Python
Practical Assignment Python
(python
` Assignment No. 01
Write a program to generate a series of float numbers from 10.0 to 50.0
with an increment of 3.5 using user defined function.
Solution:-
import pandas as pd
import numpy as np
def series1():
array1 = np.arange(10,50,3.5)
s1 = pd.Series(array1)
print(s1)
series1()
Output:-
0 10.0
1 13.5
2 17.0
3 20.5
4 24.0
5 27.5
6 31.0
7 34.5
8 38.0
9 41.5
10 45.0
11 48.5
dtype: float64
Page No.:- 01
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 02
Solution:-
import pandas as pd
s1=pd.Series(44,range(1,11))
print(s1)
Output:-
Page No.:- 02
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 03
Create a panda’s series of five items from a dictionary, display 2nd and
3rd item and then 1st and 4th item of series.
Solution:-
import pandas as pd
import numpy as np
#Creating series from a dictionary
d={'Jan':31,'Feb':28,'Mar':31,'Apr':30,'may':31}
s=pd.Series(d)
print("Series from dictionary")
print("~~~~~~~~~~~~~~~~~~~~~~~")
print(s)
print("2nd and 3rd item of the series")# Slicing
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s["Feb":"Mar"]) # using label
print(s[1:3]) # using index
print()
print("1st and 4th item of the series")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s[["Jan","Apr"]]) # using label
print(s[[0,3]]) # using index
Page No.:- 03
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
Page No.:- 04
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 04
Create a panda’s series of five items from an arrary, display 2nd and 3rd
item and then 1st and 4th item of the series.
Solution:-
import pandas as pd
import numpy as np
#Creating series from an ndarray
array1=np.array([2,3,4,5,6])
print("Series from ndarray")
print("~~~~~~~~~~~~~~~~~~~~~~~")
s1=pd.Series(array1)
print(s1)
print("2nd and 3rd item of the series")# Slicing
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s1[1:3]) # using index
print()
print("1st and 4th item of the series")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(s1[[0,3]]) # using index
Page No.:- 05
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
Series from ndarray
~~~~~~~~~~~~~~~~~~~~~~~
0 2
1 3
2 4
3 5
4 6
dtype: int32
2nd and 3rd item of the series
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 3
2 4
dtype: int32
Page No.:- 06
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 05
Create a data frame for examination results and display row labels,
column labels data types of each column and the dimensions.
Solution:-
import pandas as pd
res={'Gaurav':[76,78,75,66,68],
'Harsh':[78,56,77,49,55],
'Komal':[90,91,93,97,99],
'Radha':[55,48,59,60,66],
'Vyom':[78,79,85,88,86]}
df=pd.DataFrame(res)
print("Printing row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
idx=df.index
l=list(idx)
print(l)
print("Printing row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("[",end=" ")
for col in df.columns:
print(col,end=" ")
print("]")
print("Printing Data Types of each column")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.dtypes)
print("Printing dimensions of Data Frame")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.ndim)
Page No.:- 07
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
Gaurav Harsh Komal Radha Vyom
0 76 78 90 55 78
1 78 56 91 48 79
2 75 77 93 59 85
3 66 49 97 60 88
4 68 55 99 66 86
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[0, 1, 2, 3, 4]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Gaurav int64
Harsh int64
Komal int64
Radha int64
Vyom int64
dtype: object
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Page No.:- 08
PRACTICAL ASSIGNMENT FILE 2022-23
Assignment No. 06
Create the following DataFrame Sales containing year wise sales figures for five
salespersons in INR. Use the years as column labels, and salesperson names as row
labels.
2018 2019 2020 2021
Kapil 110 205 177 189
Kamini 130 165 175 190
Shikhar 115 206 157 179
Mohini 118 198 183 169
Solution-
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118], 2019:[205,165,175,190],
2020:[115,206,157,179], 2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
#Display row labels
print("Row Labels:\n",sales.index)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display column labels
print("Column Labels:\n",sales.columns)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display data type
print("\nDisplay column data types")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.dtypes)
print("\nDisplay the dimensions, shape, size and values of Sales")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Dimensions:",sales.ndim)
print("Shape:",sales.shape)
("Size:",sales.size)
print("Values:",sales.values)
Page No.:- 09
PRACTICAL ASSIGNMENT FILE 2022-23
Output:-
Row Labels:
Index(['Kapil', 'Kamini', 'Shikhar', 'Mohini'], dtype='object')
~~~~~~~~~~~~~~~~~~~~~~~~~~
Column Labels:
Int64Index([2018, 2019, 2020, 2021], dtype='int64')
~~~~~~~~~~~~~~~~~~~~~~~~~~
Assignment No. 07
Consider above sales dataframe and write code to display the last two
rows of Sales dataframe using different method.
Solution:-
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Display last two rows of DataFrame:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#Method 1
print("Using tail function:")
print(sales.tail(2))
#Method 2
print("Using iloc")
print(sales.iloc[-2:])
Solution:-
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
print("Display dataframe sales")
print(sales)
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
#Method 1
print(sales[[2018,2019]])
#Method 2
print(sales[sales.columns[0:2]])
#Method 3
print(sales.iloc[:, 0:2] )
Solution:-
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Transpose:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.T)
print("\nSales made by each salesman in 2018")
#Method 1
print(sales[2018])
#Method 2
print(sales.loc[:,2018])
print("Sales made by Kapil and Mohini:")
#Method 1
print(sales.loc[['Kapil','Mohini'], [2019,2020]])
#Method 2
print(sales.loc[sales.index.isin(["Kapil","Mohini"]),[2019,2020]])
print("Add Data:")
sales.loc["Nirali"]=[221, 178, 165, 177]
print(sales)
Transpose:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kapil Kamini Shikhar Mohini
2018 110 130 115 118
2019 205 165 175 190
2020 115 206 157 179
2021 118 198 183 169
sales=sales.drop("Shikhar",axis=0)
#sales.drop("shikhar")
print(sales)
sales=sales.rename({"Kamini":"Rani","Kapil":"Anil"},axis="index")
print(sales)
sales.loc[sales.index=="Mohini",2018]=150
print(sales)
Assignment No. 11
Plot the following data on a line chart and customize the chart
according to the below-given instructions:
Month January February March April May
Solution:-
import matplotlib.pyplot as pp
mon =['January','February','March','April','May']
sales = [510,350,475,580,600]
pp.plot(mon,sales,label='Sales',color='b',linestyle='dashed',marker='D')
pp.title("The Monthly Sales Report")
pp.xlabel("Months")
pp.ylabel("Sales")
pp.legend()
pp.show()
output:-
Assignment No. 12
Pratyush Garments has recorded the following data into their register for their
income from cotton clothes and jeans. Plot them on the line chart.
Solution:-
import matplotlib.pyplot as pp
day =['Monday','Tuesday','Wednesday','Thursday','Friday']
ct = [450,560,400,605,580]
js = [490,600,425,610,625]
pp.plot(day,ct,label='Cotton',color='g',linestyle='dotted',marker='+')
pp.plot(day,js,label='Food',color='m',linestyle='dashdot',marker='x')
pp.title("The Weekly Garment Orders")
pp.xlabel("Days")
pp.ylabel("Orders")
pp.legend()
pp.show()
Observe the given data for monthly views of one of the youtube channels for 6
months. Plot them on the line chart.
Solution:-
import matplotlib.pyplot as pp
months=['January','February','March','April','May','June']
views=[2500,2100,1700,3500,3000,3800]
pp.plot(months,views,label='Views State',color='r',
linestyle='dashed', linewidth=4,
marker='o', markerfacecolor='k',
markeredgecolor='b')
pp.title("Youtube Stats")
pp.xlabel("Months")
pp.ylabel("Views")
pp.legend()
pp.show()
Solutions:-
import pandas as pd
import matplotlib.pyplot as plt
# reads "MelaSales.csv" to df by giving path to the file
df=pd.read_csv("MelaSales.csv")
#create a line plot of different color for each week
df.plot(kind='line', color=['red','blue','brown'])
# Set title to "Mela Sales Report"
plt.title('Mela Sales Report')
# Label x axis as "Days"
plt.xlabel('Days')
# Label y axis as "Sales in Rs"
plt.ylabel('Sales in Rs')
#Display the figure
plt.show()
Write a Python script to display Bar plot for the “MelaSales.csv” file with column Day on x axis,
and having the following customisation:
● Changing the color of each bar to red, yellow and purple.
● Edgecolor to green
● Linewidth as 2
● Line style as "--"
File name : MelaSales.csv
Week1 Week2 Week3 Day
5000 4000 4000 Monday
5900 3000 5800 Tuesday
6500 5000 3500 Wednesday
3500 5500 2500 Thursday
4000 3000 3000 Friday
5300 4300 5300 Saturday
7900 5900 6000 Sunday
Solution:-
import pandas as pd
import matplotlib.pyplot as plt
df= pd.read_csv('MelaSales.csv')
# plots a bar chart with the column "Days" as x axis
df.plot(kind='bar',x='Day',title='Mela Sales Report',color=['red',
'yellow','purple'],edgecolor='Green',linewidth=2,linestyle='--')
#set title and set ylabel
plt.ylabel('Sales in Rs')
plt.show()
Display histogram of data provided for height and weight of few persons
in dataframe.
Solution:-
import pandas as pd
import matplotlib.pyplot as plt
data = {'Name':['Arnav', 'Sheela', 'Azhar', 'Bincy', 'Yash','Nazar'],
'Height' : [60,61,63,65,61,60],
'Weight' : [47,89,52,58,50,47]}
df=pd.DataFrame(data)
df.plot(kind='hist')
plt.show()
Output:-