Python Prog Lab Manual KR21
Python Prog Lab Manual KR21
(KMIT)
(Autonomous)
LAB MANUAL
PYTHON PROGRAMMING
1
INDEX
I List of Experiments ii
II V/M /POs/PSOs/PEOs iv
III Syllabus ix
i
List of Experiments
ii
b) Given a string S having characters from English alphabets ['a' - 'z'] and '.'
as the special character (without quotes). Write a program to construct the
lexicographically smallest palindrome by filling each of the faded character
('.') with a lower case alphabet.
c) Given an alphanumeric string S, write a program to extract maximum
numeric value from that string. All the alphabets are in lower case. Take the
maximum consecutive digits as a single number.
a) Given a list A of elements of length N, ranging from 0 to N-1. All
elements may not be present in the array. If the element is not present then
there will be -1 present in the array. Rearrange the array such that A[i] = i
and if i is not present then insert -1 at that place.
b) Given an array A of N numbers, you have to write a program which
4 prints the sum of the elements of array A with the corresponding elements of 12
the reverse of array A. If array A has elements [1,2,3], then reverse of the
array A will be [3,2,1] and the resultant array should be [4,4,4].
c) Given a list A of N distinct integers, write a program to sort the list by
moving an element to the end of the list. Find the minimum number of
moves required to sort the list using this method in ascending order.
a) A lower triangular matrix is a square matrix (where the number of rows
and columns are equal) where all the elements above the diagonal are zero.
Write a program to convert a given square matrix into a lower triangular
5 matrix. 15
iii
Import the iris dataset from https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data
a) Find the mean, median, standard deviation of iris's ‘sepal length’ (1st
8 23
column).
b) Filter the rows of iris_2d that has petallength (3rd column) > 1.5
and sepallength (1st column) < 5.0
Import the Cars93 dataset into a data frame from
https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv
a) Check if dataframe has any missing values.
9 25
b) Count the number of missing values in each column of dataframe. Which
column has the maximum number of missing values?
c) Replace missing values in Min.Price and Max.Price columns with their
respective mean.
a) A number raised to the third power is a cube. Plot the first five cubic
10 numbers, and then plot the first 5000 cubic numbers. 29
b) Colored Cubes: Apply a colormap to your cubes plot.
Sitka is in a temperate rainforest, so it gets a fair amount of rainfall. In the
data file sitka_weather_2018_simple.csv is a header called PRCP, which
11 32
represents daily rainfall amounts. Make a visualization focusing on the data
in this column.
iv
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407
To be the fountain head of latest technologies, producing highly skilled, globally competent
engineers.
• To establish Industry Institute Interaction to make students ready for the industry.
• To encourage and enable students to not merely seek jobs from the industry but also to create
new enterprises
• To induce a spirit of nationalism which will enable the student to develop, understand India’s
challenges and to encourage them to develop effective solutions.
• To support the faculty to accelerate their learning curve to deliver excellent service to
students
v
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407
To be among the region's premier teaching and research Computer Science and Engineering
departments producing globally competent and socially responsible graduates in the most
conducive academic environment.
• To provide faculty with state of the art facilities for continuous professional development and
research, both in foundational aspects and of relevance to emerging computing trends.
• To impart skills that transform students to develop technical solutions for societal needs and
inculcate entrepreneurial talents.
• To inculcate an ability in students to pursue the advancement of knowledge in various
specializations of Computer Science and Engineering and make them industry-ready.
• To engage in collaborative research with academia and industry and generate adequate
resources for research activities for seamless transfer of knowledge resulting in sponsored
projects and consultancy.
• To cultivate responsibility through sharing of knowledge and innovative computing solutions
that benefit the society-at-large.
• To collaborate with academia, industry and community to set high standards in academic
excellence and in fulfilling societal responsibilities.
vi
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407
vii
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407
PSO2: Shall have expertise on the evolving technologies like Python, Machine Learning, Deep
Learning, Internet of Things (IOT), Data Science, Full stack development, Social Networks,
Cyber Security, Big Data, Mobile Apps, CRM, ERP etc.
viii
KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY
(Approved by AICTE & Govt of T.S and Affiliated to
JNTUH) 3-5-1026, Narayanaguda, Hyderabad-29. Ph:
040-23261407
PEO2: Graduates will try and provide solutions to challenging problems in their profession by
applying computer engineering principles.
PEO3: Graduates will engage in life-long learning and professional development by rapidly
adapting changing work environment.
PEO4: Graduates will communicate effectively, work collaboratively and exhibit high levels of
professionalism and ethical responsibility.
ix
SYLLABUS
Python Programming Lab
B.TECH I Year II Sem
1. a) Arun is working in an office which is N blocks away from his house. He wants to
minimize the time it takes him to go from his house to the office. He can either take the
office cab or he can walk to the office. Arun's velocity is V1 m/s when he is walking. The
cab moves with velocity V2 m/s but whenever he calls for the cab, it always starts from the
office, covers N blocks, collects Arun and goes back to the office. The cab crosses a total
distance of N meters when going from office to Arun's house and vice versa, whereas Arun
covers a distance of (√2)(2)*N while walking. Write a program to help Arun to find whether
he should walk or take a cab to minimize the time.
b) There is a robot which wants to go the charging point to charge itself. The robot moves in
a 2-D plane from the original point (0,0). The robot can move toward UP, DOWN, LEFT and
RIGHT with given steps. The trace of robot movement is shown as the following: UP 5
DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 The numbers after
the direction are steps. Write a program to compute the distance between the current position
after a sequence of movement and original point. If the distance is a float, then just print the
nearest integer (use round() function for that and then convert it into an integer).
2. a) Write a program that prints the numbers from 1 to 100. But for multiples of three
print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which
are multiples of both three and five print.
b) Write a program to check whether a given positive number is a Harshad Number or not. A
harshad number is an integer that is divisible by the sum of its digits. For example 171 is a
Harshad Number because the sum of digits is 9(1+7+1) and 171 is divisible by 9.
c) Given a number n, write an efficient function to print all unique prime factors of n. For
example, if the input number is 315, then output should be "3 5 7".
d) A semiprime number is an integer which can be expressed as a product of two distinct
primes. For example 15 = 3*5 is a semiprime number but 9 = 3*3 is not.
Given an integer number N, find whether it can be expressed as a sum of two semi-primes or
not (not necessarily distinct).
3. a) You are given a string which is a password, write a program to check if the password
entered by the user is a valid or not. If it is a valid password then print “valid” else print
“Invalid”
Rules of the password:
i) Minimum length is 6 characters and maximum length is 15 characters.
ii) It should have a minimum of one Capital Letter, One digit and one special symbol
iii) Special symbols allowed are only (*, @, #)
x
b) Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the special
character (without quotes). Write a program to construct the lexicographically smallest
palindrome by filling each of the faded character ('.') with a lower case alphabet.
The smallest lexicographical order is an order relation where string s is smaller than t, given
the first character of s (s1) is smaller than the first character of t (t1), or in case they are
equivalent, the second character, etc.
c) Given an alphanumeric string S, write a program to extract maximum numeric value from
that string. All the alphabets are in lower case. Take the maximum consecutive digits as a
single number.
4. a) Given a list A of elements of length N, ranging from 0 to N-1. All elements may not be
present in the array. If the element is not present then there will be -1 present in the array.
Rearrange the array such that A[i] = i and if i is not present then insert -1 at that place.
b) Given an array A of N numbers, you have to write a program which prints the sum of the
elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant
array should be [4,4,4].
c) Given a list A of N distinct integers, write a program to sort the list by moving an element
to the end of the list. Find the minimum number of moves required to sort the list using this
method in ascending order.
5. a) A lower triangular matrix is a square matrix (where the number of rows and columns are
equal) where all the elements above the diagonal are zero. Write a program to convert a
given square matrix into a lower triangular matrix.
b) Given a square matrix, write a program to print it in a counter-clockwise spiral form.
6. a) Given a number n, define a function named printDict() which can print a dictionary where
the keys are numbers between 1 and n (both included) and the values are square of keys. The
function printDict() doesn't take any argument.
b) Write a program to find the most common scores in the list of scores given in sorted order
based on occurrence from largest to smallest. If any of scores are having same occurrence
then consider the largest score first.
Input format: First line contains the list of scores and next line contains a number (k) which
represent the top most scores to display.
Output format: display the k top most scores.
7. a) Write a program that loads roll numbers and names from the given CSV file into
dictionary where data is organized as one row per record. It takes a roll number or name as
input and prints the corresponding other value from dictionary.
b) Write a program to find the frequency of distinct words in the given text file and store the
words along with the frequency in a CSV file.
xi
8. Import the iris dataset from https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data
a) Find the mean, median, standard deviation of iris's ‘sepal length’ (1st column).
b) Filter the rows of iris_2d that has petallength (3rd column) > 1.5 and sepallength
(1st column) < 5.0
9. Import the Cars93 dataset into a data frame from
https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv
a) Check if dataframe has any missing values.
b) Count the number of missing values in each column of dataframe. Which column has the
maximum number of missing values?
c) Replace missing values in Min.Price and Max.Price columns with their respective mean.
10. a) A number raised to the third power is a cube. Plot the first five cubic numbers, and then
plot the first 5000 cubic numbers.
b) Colored Cubes: Apply a colormap to your cubes plot.
11. Sitka is in a temperate rainforest, so it gets a fair amount of rainfall. In the data file
sitka_weather_2018_simple.csv is a header called PRCP, which represents daily rainfall
amounts. Make a visualization focusing on the data in this column.
xii
Course Objectives: To learn
1. Understand the usage of data types, loops and conditional statements and functions.
2. Understand Lists, Dictionaries and Regular expressions in Python.
3. Handle Strings and Files in Python.
4. Learn the implantation of Python modules like Numpy, Pandas, matplotlib.
Course Outcomes: After learning the contents of this course the student is able to
CO1. Examine Python syntax and semantics and be fluent in the use of Python flow control and
functions. Demonstrate proficiency in handling Strings and File Systems.
CO2. Create, run and manipulate Python Programs using core data structures like Lists, Tuples,
and Dictionaries.
CO3. Implement exemplary applications related to Numpy, Pandas and matplotlib in Python.
CO VS PO MAPPING:
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Python CO1 3 2 2 2 2 2
Programming
Lab CO2 3 2 3 2 3 3
CO3 3 3 3 3 3 3
CO VS PSO MAPPING:
PSO-1 PSO-2
CO1 1 3
CO2 2 3
CO3 2 3
xiii
Experiment 1
1 a) Arun is working in an office which is N blocks away from his house. He wants to
minimize the time it takes him to go from his house to the office. He can either take the
office cab or he can walk to the office. Arun’s velocity is V1 m/s when he is walking. The
cab moves with velocity V2 m/s but whenever he calls for the cab, it always starts from the
office, covers N blocks, collects Arun and goes back to the office. The cab crosses a total
distance of N meters when going from office to Arun’s house and vice versa, whereas Arun
covers a distance of (√2)*N while walking. Write a program to help Arun to find whether
he should walk or take a cab to minimize the time.
Program:
import math
N = int(input("Enter number of blocks: "))
V1 = int(input("Enter walking velocity: "))
V2 = int(input("Enter cab velocity: "))
Walk_time = math.sqrt(2)* N / V1
Cab_time = 2 * N / V2
if (Walk_time<Cab_time):
print("Walk")
else:
print("Cab")
1
1 b) There is a robot which wants to go the charging point to charge itself. The robot moves
in a 2-D plane from the original point (0,0). The robot can move toward UP, DOWN, LEFT
and RIGHT with given steps. The trace of robot movement is shown as the following: UP 5
DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 The numbers
after the direction are steps. Write a program to compute the distance between the current
position after a sequence of movement and original point. If the distance is a float, then just
print the nearest integer (use round() function for that and then convert it into an integer).
Program:
from math import *
x,y=0,0
n=int(input())
for i in range(n):
d,m = input().split()
if d=="UP":
y=y+int(m)
elif d=="DOWN":
y=y-int(m)
elif d=="LEFT":
x=x-int(m)
else:
x=x+int(m)
dist = sqrt(x*x+y*y)
print("Distance=",round(dist))
2
Experiment 2
2 a) Write a program that prints the numbers from 1 to 100. But for multiples of three
print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers
which are multiples of both three and five print.
Program:
for i in range(1,101):
if(i%15==0):
print("FizzBuzz")
elif(i%5==0):
print("Buzz")
elif(i%3==0):
print("Fizz")
else:
print(i)
Sample Input & Output:
1 26 Fizz 76
2 Fizz 52 77
Fizz 28 53 Fizz
4 29 Fizz 79
Buzz FizzBuzz Buzz Buzz
Fizz 31 56 Fizz
7 32 Fizz 82
8 Fizz 58 83
Fizz 34 59 Fizz
Buzz Buzz FizzBuzz Buzz
11 Fizz 61 86
Fizz 37 62 Fizz
13 38 Fizz 88
14 Fizz 64 89
FizzBuzz Buzz Buzz FizzBuzz
16 41 Fizz 91
17 Fizz 67 92
Fizz 43 68 Fizz
19 44 Fizz 94
Buzz FizzBuzz Buzz Buzz
Fizz 46 71 Fizz
22 47 Fizz 97
23 Fizz 73 98
Fizz 49 74 Fizz
Buzz Buzz FizzBuzz Buzz
3
2 b) Write a program to check whether a given positive number is a Harshad Number or
not. A harshad number is an integer that is divisible by the sum of its digits. For example
171 is a Harshad Number because the sum of digits is 9(1+7+1) and 171 is divisible by 9.
Program:
4
2 c) Given a number n, write an efficient function to print all unique prime factors of n. For
example, if the input number is 315, then output should be "3 5 7".
Program:
def prime(num):
for j in range(2,num):
if(num%j==0):
return False
return True
def primeFactors(n):
for i in range(2,n+1):
if(n%i==0 and prime(i)):
print(i,end=" ")
5
2 d) A semiprime number is an integer which can be expressed as a product of two distinct
primes. For example 15 = 3*5 is a semiprime number but 9 = 3*3 is not.
Given an integer number N, find whether it can be expressed as a sum of two semi-primes
or not (not necessarily distinct).
Program:
import math
MAX=200
arr=[]
sprime=[False]*(MAX)
6
break
i=i+1
if(ans):
print(n,"is sum of two semi-primes")
else:
print(n,"is not sum of two semi-primes")
7
Experiment 3
3 a) You are given a string which is a password, write a program to check if the password
entered by the user is a valid or not. If it is a valid password then print “valid” else print
“Invalid”
Rules of the password:
i) Minimum length is 6 characters and maximum length is 15 characters.
ii) It should have a minimum of one Capital Letter, One digit and one special symbol
iii) Special symbols allowed are only (*, @, #)
Program:
import re
password = input("Enter a password: ")
flag = 0
while True:
if (len(password)<6 and len(password)>15):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif not re.search("[*@#]", password):
flag = -1
break
elif re.search("\s", password):
flag = -1
break
else:
8
flag = 0
print("Valid Password")
break
if flag ==-1:
print("Not a Valid Password")
9
3 b) Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the
special character (without quotes). Write a program to construct the lexicographically
smallest palindrome by filling each of the faded character ('.') with a lower case alphabet.
The smallest lexicographical order is an order relation where string s is smaller than t,
given the first character of s (s1) is smaller than the first character of t (t1), or in case they
are equivalent, the second character, etc.
Program:
s = input("Enter a string: ")
alpha = []
for i in range(97,123):
alpha.append(chr(i))
for c in alpha:
new = s.replace('.',c)
if new==new[::-1]:
print(new)
break
else:
print("Not possible to make the string as palindrome")
10
3 c) Given an alphanumeric string S, write a program to extract maximum numeric value
from that string. All the alphabets are in lower case. Take the maximum consecutive digits
as a single number.
Program:
def extractMaximum(s):
num, res = 0, 0
for i in range(len(s)):
if s[i] >= "0" and s[i] <= "9":
num = num * 10 + int(int(s[i]) - 0)
else:
res = max(res, num)
num = 0
11
Experiment 4
4 a) Given a list A of elements of length N, ranging from 0 to N-1. All elements may not be
present in the array. If the element is not present then there will be -1 present in the array.
Rearrange the array such that A[i] = i and if i is not present then insert -1 at that place.
Program:
12
4 b) Given an array A of N numbers, you have to write a program which prints the sum of
the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant
array should be [4,4,4].
Program:
n = int(input("Enter N value: "))
array = input("Enter array elements: ")
list1 = list(map(int,array.split()))
list2 = list1[::-1]
print("Resultant Array:",end=" ")
for x in range(n):
print(list1[x]+list2[x],end=" ")
13
4 c) Given a list A of N distinct integers, write a program to sort the list by moving an
element to the end of the list. Find the minimum number of moves required to sort the list
using this method in ascending order.
Program:
14
Experiment 5
5 a) A lower triangular matrix is a square matrix (where the number of rows and columns
are equal) where all the elements above the diagonal are zero. Write a program to convert
a given square matrix into a lower triangular matrix.
Program:
n = int(input("Enter number of rows: "))
mat = []
print("Enter elements:")
for i in range(n):
mat.append(input().split())
for i in range(n):
for j in range(n):
if j>i:
mat[i][j]=0
print("Lower Triangular matrix:")
for row in mat:
print(*row)
15
5 b) Given a square matrix, write a program to print it in a counter-clockwise spiral form.
Program:
a = int(input("Enter number of rows: "))
mat=[]
print("Enter elements:")
for i in range(0,a):
l = list(map(int, input ().split ()))
mat.append(l)
m,n = a,a
k,l = 0,0
count = 0
total = a*a
print("Counter-clockwise spiral form:")
while (k < m and l < n) :
if (count == total) :
break
for i in range(k, m) :
print(mat[i][l], end=" ")
count += 1
l += 1
if (count == total) :
break
16
if (count == total) :
break
if (k < m) :
for i in range(m - 1, k - 1, -1) :
print(mat[i][n - 1], end = " ")
count += 1
n -= 1
if (count == total) :
break
if (l < n) :
for i in range(n - 1, l - 1, -1) :
print( mat[k][i], end = " ")
count += 1
k += 1
17
Experiment 6
6 a) Given a number n, define a function named printDict() which can print a dictionary
where the keys are numbers between 1 and n (both included) and the values are square of
keys. The function printDict() doesn't take any argument.
Program:
def printDict():
n = int(input("Enter a number: "))
d=dict()
for i in range(1,n+1):
d[i]=i**2
print("The resultant dictionary is")
print(d)
printDict()
18
6 b) Write a program to find the most common scores in the list of scores given in sorted
order based on occurrence from largest to smallest. If any of scores are having same
occurrence then consider the largest score first.
Input format: First line contains the list of scores and next line contains a number (k)
which represent the top most scores to display.
Output format: display the k top most scores.
Program:
scores = [int(x) for x in input().split()]
k = int(input())
unique_scores = set(scores)
freq = dict()
for s in unique_scores:
freq[s] = scores.count(s)
top_scores = list(freq2.keys())
print(*top_scores[:k])
Sample Input:
1222234788
4
Sample output:
2874
19
Experiment 7
7 a) Write a program that loads roll numbers and names from the given CSV file into
dictionary where data is organized as one row per record. It takes a roll number or name
as input and prints the corresponding other value from dictionary.
Program:
import csv
mydict = {}
reader = csv.reader(inp)
if n in dict_from_csv:
else:
Name : A NEELANJANA
20
7 b) Write a program to find the frequency of distinct words in the given text file and store
the words along with the frequency in a CSV file.
Program:
import re
import string
frequency = {}
text_string = document_text.read().lower()
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
print(words, frequency[words])
21
Output:
welcome 2
kmit 1
python 1
programming 1
lab 1
22
Experiment 8
Import the iris dataset from https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data
8 a) Find the mean, median, standard deviation of iris's ‘sepal length’ (1st column).
Program:
import numpy as np
import pandas as pd
iris_2d=pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-
databases/iris/iris.data",header=None)
iris_2d.columns=['SpealLength','SpealWidth','PetalLength','PetalWidth','Species']
23
8 b) Filter the rows of iris_2d that has petallength (3rd column) > 1.5 and sepallength
(1st column) < 5.0
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d[condition]
24
Experiment 9
Import the Cars93 dataset into a data frame from
https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv
9 a) Check if dataframe has any missing values.
Program:
import pandas as pd
df=pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv")
df.isnull()
25
9 b) Count the number of missing values in each column of dataframe. Which column has
the maximum number of missing values?
Program:
print("Number of missing values in each column:")
print(df.isnull().sum())
print("Columnn with maximum null values : ", df.count().idxmin())
Sample output:
Number of missing values in each column:
Manufacturer 4
Model 1
Type 3
Min.Price 7
Price 2
Max.Price 5
MPG.city 9
MPG.highway 2
AirBags 6
DriveTrain 7
Cylinders 5
EngineSize 2
Horsepower 7
RPM 3
Rev.per.mile 6
Man.trans.avail 5
Fuel.tank.capacity 8
Passengers 2
Length 4
Wheelbase 1
Width 6
Turn.circle 5
Rear.seat.room 4
26
Luggage.room 19
Weight 7
Origin 5
Make 3
dtype: int64
Columnn with maximum null values : Luggage.room
27
9 c) Replace missing values in Min.Price and Max.Price columns with their respective mean.
Program:
df["Min.Price"].fillna(df["Min.Price"].mean())
df["Max.Price"].fillna(df["Max.Price"].mean())
Sample output:
0 12.900000
1 29.200000
2 25.900000
3 17.118605
4 17.118605
...
88 16.600000
89 17.600000
90 22.900000
91 21.800000
92 24.800000
Name: Min.Price, Length: 93, dtype: float64
0 18.800000
1 38.700000
2 32.300000
3 44.600000
4 21.459091
...
88 22.700000
89 22.400000
90 23.700000
91 23.500000
92 28.500000
Name: Max.Price, Length: 93, dtype: float64
28
Experiment 10
10 a) A number raised to the third power is a cube. Plot the first five cubic numbers, and
then plot the first 5000 cubic numbers.
Program
from matplotlib import pyplot as plt
x=[1,2,3,4,5]
x_cube = [1, 8, 27, 64, 125]
plt.scatter(x,x_cube)
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
29
/*plot the first 5000 cubic numbers*/
Program
from matplotlib import pyplot as plt
ylist=list(range(5001))
y_cube = [y**3 for y in ylist]
plt.scatter(ylist,y_cube)
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
30
10 b) Colored Cubes: Apply a colormap to your cubes plot.
Program
x_values = list(range(5001))
cubes = [x**3 for x in x_values]
plt.scatter(x_values, cubes, edgecolor='none', c=cubes, cmap=plt.cm.BuGn, s=40)
plt.title("Cubes", fontsize=24)
plt.xlabel('Value', fontsize=14)
plt.ylabel('Cube of Value', fontsize=14)
plt.tick_params(axis='both', labelsize=14)
plt.axis([0, 5100, 0, 5100**3])
plt.show()
31
Experiment 11
Sitka is in a temperate rainforest, so it gets a fair amount of rainfall. In the data file
sitka_weather_2018_simple.csv is a header called PRCP, which represents daily rainfall
amounts. Make a visualization focusing on the data in this column.
Program
import matplotlib.pyplot as plt
import pandas as pd
url = 'https://raw.githubusercontent.com/ehmatthes/pcc_2e/master/chapter_16/the_csv_file_form
at/data/sitka_weather_2018_simple.csv'
df_sitka = pd.read_csv(url)
df_sitka['PRCP'].plot(kind="hist",bins=50,figsize=(6,4)) #histogram
df_sitka.plot(x='DATE', y='PRCP', kind='scatter',
figsize=(6,5),
title='RainFall in 2018') #scatter
df_sitka.boxplot(column='PRCP', by='TMAX', figsize=(10,6)) #boxplot
df_sitka[['DATE','PRCP']].groupby('DATE').mean().sort_values(by='PRCP', ascending=False).p
lot.bar(figsize=(10,6), rot=10, title='Average Rain fall in stations wrt DATE') #bargraph
df_sitka[['TMAX','PRCP']].groupby('TMAX').mean().sort_values(by='PRCP', ascending=False).
plot.bar(figsize=(10,6), rot=10, title='Average Rain fall in stations wrt DATE')
Sample input & output
1. histogram
32
2. scatter plot
3. boxplot
33
4. bar graph : DATE,PRCP
34