Python Practical Questions
Python Practical Questions
[1] Write a program to generate a series of float numbers from 41.0 to 60.0 with an increment of 2.5 each.
Solution:
import pandas as pd
import numpy as np
n = np.arange(41,60,2.5)
s = pd.Series(n)
print(s)
The Output is:
[2] Write a program to generate a series of 10 numbers with a scalar value of 44.
Solution:
import pandas as pd
print(pd.Series(44,range(1,11)))
OUTPUT:
Original Series:
0 55
1 45
2 44
3 65
4 74
5 75
6 36
7 25
8 98
9 45
10 32
11 77
dtype: int64
75th Percentile:
74.25
[7] Create a data frame and print it along with their index using iteritems().
Solution:
import pandas as pd
sc_4yrs={2016:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
2017:{'Virat Kohli':2818,'Rohit Sharma':2613,'Shikhar Dhawan':2295},
2018:{'Virat Kohli':2735,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
2019:{'Virat Kohli':2455,'Rohit Sharma':2310,'Shikhar Dhawan':1844}}
df=pd.DataFrame(sc_4yrs)
print(df)
print("--------------------------------------------------------------")
for (year,runs) in df.iteritems():
print("Year:",year)
print(runs)
[8] 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.
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)
print("Size:",sales.size)
print("Values:",sales.values)
[9] Consider the above dataframe and write code to do the following:
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:])
#With Specific Columns, I have printed two columns
print("Specific Columns")
print(Sales.iloc[-2:,-2:])
print("Display first two columns of Dataframe:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#Method 1
print(Sales[[2014,2015]])
#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)
print("Delete Data for 2018:")
sales=sales.drop(columns=2018)
print(sales)
Sales.drop(columns=2018,inplace=True)
print(Sales)
sales=sales.drop("Shikhar",axis=0)
#sales.drop("kinshuk")
print(sales)
sales=sales.rename({"Kamini":"Rani","Kapil":"Anil"},axis="index")
print(sales)
sales.loc[sales.index=="Mohini",2018]=150
print(sales)
[11] Plot the following data on a line chart and customize the chart according to the
below-given instructions:
# x axis values
x1 = [2,4,7,8,10,12] and x2 = [3,4,6,8,10,12]
# corresponding y axis values
y1 = [2,6,3,5,2,6] and y2 = [4,8,3,9,4,11]
Ensure to display an appropriate title, x and y limits, x and y labels, legend and grid.
# x axis values
x1 = [2,4,7,8,10,12]
x2 = [3,4,6,8,10,12]
# corresponding y axis values
y1 = [2,6,3,5,2,6]
y2 = [4,8,3,9,4,11]
# plotting the points
plt.plot(x1, y1,
label = 'first', color='green', linestyle='dashed', linewidth=3,
marker='o', markerfacecolor='pink', markersize=7)
plt.plot(x2, y2,
label = 'second', color='red', linestyle='dotted', linewidth=3,
marker='D', markerfacecolor='gold', markersize=7)
[12] Plot the following data on a bar graph and customize the chart according to the
below-given instructions:
# x axis values
x = [1, 2, 3, 4, 5]
# corresponding y axis values
y = [10, 24, 36, 40, 5]
Ensure to display an appropriate title, tick labels, x and y labels.
# x-axis values
x = [1,2,3,4,5]
# y-axis values
y = [10, 24, 36, 40, 5]
# x-axis label
plt.xlabel('S.No.')
# y-axis label
plt.ylabel('Height (cms)')
[13] Plot the following data on a histogram and customize the chart according to the
below-given instructions:
marks = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100] with 5 intervals.
Ensure to display an appropriate title, x and y labels.
import numpy as np
import matplotlib.pyplot as plt
marks = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
bins = 5
plt.hist(marks, bins, color='blue', alpha=0.7, edgecolor='black')
# x-axis label
plt.xlabel('Marks', fontweight ='bold', fontsize = 12)
# y-axis label
plt.ylabel('No. of Students', fontweight ='bold', fontsize = 12)
# Giving a title
plt.title('Frequency Distribution',
fontweight = 'bold', fontsize = 15)
[14] Plot the following data on a line chart and customize the chart according to the
below-given instructions:
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:
[15] Pratyush Garments has recorded the following data into their register for their income
from cotton clothes and jeans. Plot them on the line chart.
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()
[16] 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
mon =['January','February','March','April','May','June']
views = [2500,2100,1700,3500,3000,3800]
pp.plot(mon,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()
[17] Observe the following data and plot data according to the given instructions:
1. Create a bar chart to display data of Virat Kohli & Rohit Sharma.
2. Customize the chart in this manner
1. Use different widths
2. Use different colors to represent different years score
3. Display appropriate titles for the axis and chart
4. Show legends
5. Create a bar chart to display data from Steve Smith, Kane Williamson & Jos Butler.
Customize Chart as per your wish.
6. Display data of all players for the specific year.