You are on page 1of 16

ID NUMBER -> 170040841

TECHNICAL SKILLING
CO-3
1. Write a Python GUI program to import Tkinter package and create a window. Set its
title and add a label to the window?
import tkinter as tk
parent = tk.Tk()
parent.title("-Welcome to Python tkinter Basic exercises-")
my_label = tk.Label(parent, text="Label widget")
my_label.grid(column=0, row=0)
parent.mainloop()
OUTPUT:

2. Write a Python GUI program to create three single line text-box to accept a value
from the user using tkinter module?

import tkinter as tk
parent = tk.Tk()
parent.geometry("400x250")
name = tk.Label(parent, text = "Name").place(x = 30, y = 50)
email = tk.Label(parent, text = "User ID").place(x = 30, y =
90)
password = tk.Label(parent, text = "Password").place(x = 30,
y = 130)
sbmitbtn = tk.Button(parent, text = "Submit", activebackground
= "green", activeforeground = "blue").place(x = 120, y = 170)
entry1 = tk.Entry(parent).place(x = 85, y = 50)
entry2 = tk.Entry(parent).place(x = 85, y = 90)
entry3 = tk.Entry(parent).place(x = 90, y = 130)
parent.mainloop()
OUTPUT:

3. Write a NumPy program to create a 8x8 matrix and fill it with a checkerboard
pattern?

import numpy as np
x = np.ones((3,3))
print("Checkerboard pattern:")
x = np.zeros((8,8),dtype=int)
x[1::2,::2] = 1
x[::2,1::2] = 1
print(x)

OUTPUT:

Checkerboard pattern:

[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]

4. Write a NumPy program to create a structured array from given student name,
height, class and their data types. Now sort the array on height?

import numpy as np
data_type = [('name', 'S11'), ('class', int), ('height', float
)]
students_details = [('Vamsi', 5, 48.5), ('Rakesh', 6, 52.5),('
Yeswanth', 5, 42.10), ('Nikhil', 5, 40.11)]
# create a structured array
students = np.array(students_details, dtype=data_type)
print("Original array:")
print(students)
print("Sorted Array As Per Height")
print(np.sort(students, order='height'))

OUTPUT:

Original array:
[(b'Vamsi', 5, 48.5 ) (b'Rakesh', 6, 52.5 ) (b'Yeswanth', 5,
42.1 )
(b'Nikhil', 5, 40.11)]
Sorted Array As Per Height
[(b'Nikhil', 5, 40.11) (b'Yeswanth', 5, 42.1 ) (b'Vamsi', 5,
48.5 )
(b'Rakesh', 6, 52.5 )]

5. Write a NumPy program to create a structured array from given student name,
height, class and their data types. Now sort by class, then height if class are equal?

import numpy as np
data_type = [('name', 'S15'), ('class', int), ('height', float
)]
students_details = [('Vamsi', 5, 48.5), ('Rakesh', 6, 52.5),('
Yeswanth', 5, 42.10), ('Nikhil', 5, 40.11)]
# create a structured array
students = np.array(students_details, dtype=data_type)
print("Original Array:")
print(students)
print("Sorted Array, then height if class are equal:")
print(np.sort(students, order=['class', 'height']))

OUTPUT:

Original Array:
[(b'Vamsi', 5, 48.5 ) (b'Rakesh', 6, 52.5 ) (b' Yeswanth', 5,
42.1 )
(b'Nikhil', 5, 40.11)]
Sorted Array, then height if class are equal:
[(b'Nikhil', 5, 40.11) (b' Yeswanth', 5, 42.1 ) (b'Vamsi', 5,
48.5 )
(b'Rakesh', 6, 52.5 )]

6. Write a NumPy program to partition a given array in a specified position and move
all the smaller elements values to the left of the partition, and the remaining values to
the right, in arbitrary order (based on random choice)?

import numpy as np
nums = np.array([70, 50, 20, 30, -11, 60, 50, 40])
print("Original array:")
print(nums)
print("\nAfter partitioning on 4 the position:")
print(np.partition(nums, 2))

OUTPUT:

Original array:
[-40 -30 -20 -10 0 10 20 30 40]

After The Change


[-40 -30 -20 -10 0 10 20 30 40]

7. Write a NumPy program to get the element-wise remainder of an array of division?


import numpy as np
x = np.arange(7)
print("Original Array:")
print(x)
print("Element-wise remainder of division:")
print(np.remainder(x, 5))

OUTPUT:

Original array:
[0 1 2 3 4 5 6]
Element-wise remainder of division:
[0 1 2 3 4 0 1]

8. Write a NumPy program to get the floor, ceiling and truncated values of the elements
of a numpy array?

import numpy as np
x = np.array([-1.9, -1.7, -0.6, 0.5, 1.4, 1.3, 2.2])
print("Original array:")
print(x)
print("Floor values:")
print(np.floor(x))
print("Ceil values:")
print(np.ceil(x))
print("Truncated values:")
print(np.trunc(x))

OUTPUT:

Original array:
[-1.9 -1.7 -0.6 0.5 1.4 1.3 2.2]
Floor values:
[-2. -2. -1. 0. 1. 1. 2.]
Ceil values:
[-1. -1. -0. 1. 2. 2. 3.]
Truncated values:
[-1. -1. -0. 0. 1. 1. 2.]

9. Write a NumPy program to test element-wise of a given array for finiteness (not
infinity or not Not a Number), positive or negative infinity, for NaN, for NaT (not a
time), for negative infinity, for positive infinity?

import numpy as np
print("\nTest element-wise for finiteness:")
print(np.isfinite(1))
print(np.isfinite(0))
print(np.isfinite(np.nan))
print("\nTest element-
wise for positive (or) negative infinity number:")
print(np.isinf(np.inf))
print(np.isinf(np.nan))
print(np.isinf(np.NINF))
print("Test element-wise for NaN:")
print(np.isnan([np.log(-1.),1.,np.log(0)]))
print("Test element-wise for NaT (not a time):")
print(np.isnat(np.array(["NaT", "2016-01-
01"], dtype="datetime64[ns]")))
print("Test element-wise for negative infinity:")
x = np.array([-np.inf, 0., np.inf])
y = np.array([2, 2, 2])
print(np.isneginf(x, y))
print("Test element-wise for positive infinity:")
x = np.array([-np.inf, 0., np.inf])
y = np.array([2, 2, 2])
print(np.isposinf(x, y))

OUTPUT:

Test element-wise for finiteness:


True
True
False

Test element-wise for positive (or) negative infinity number:


True
False
True
Test element-wise for NaN:
[ True False False]
Test element-wise for NaT (not a time):
[ True False]
Test element-wise for negative infinity:
[1 0 0]
Test element-wise for positive infinity:
[0 0 1]

10.Write a Python program to search the Street address, name from a given location
information using Nominatim API and GeoPy package?

from geopy.geocoders import Nominatim


geolocator = Nominatim(user_agent="geoapiExercises")
ladd1 = "27488 Stanford Avenue, North Dakota"
print("Location address:",ladd1)
location = geolocator.geocode(ladd1)
print("Street address, street name: ")
print(location.address)
ladd2 = "380 New York St, Redlands, CA 92373"
print("\nLocation address:",ladd2)
location = geolocator.geocode(ladd2)
print("Street address, street name: ")
print(location.address)
ladd3 = "1600 Pennsylvania Avenue NW"
print("\nLocation address:",ladd3)
location = geolocator.geocode(ladd3)
print("Street address, street name: ")
print(location.address)

OUTPUT:

Location address: 27488 Stanford Avenue, North Dakota


Street address, Street name:
Stanford Avenue, Bowdon, Wells County, North Dakota, 58418,
United States of America

Location address: 380 New York St, Redlands, CA 92373


Street address, street name:
Esri Building C, 380, New York Street, Esri Inc., Lugonia
Homes, Redlands, San Bernardino County, California, 92373-
4709, United States of America

Location address: 1600 Pennsylvania Avenue NW


Street address, street name:
White House, 1600, Pennsylvania Avenue Northwest, Washington,
District of Columbia, 20500, United States of America

11.Write a Python function to get the city, state and country name of a specified latitude
and longitude using Nominatim API and Geopy package?

from geopy.geocoders import Nominatim


geolocator = Nominatim(user_agent="geoapiExercises")
def city_state_country(coord):
location = geolocator.reverse(coord, exactly_one=True)
address = location.raw['address']
city = address.get('city', '')
state = address.get('state', '')
country = address.get('country', '')
return city, state, country
print(city_state_country("47.470706, -99.704723"))

OUTPUT:
('', 'North Dakota', 'United States of America')

12.Write a Python program to get the number of paragraph tags of a given html
document?

from bs4 import BeautifulSoup


html_doc = """
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<title>An example of HTML page</title>
</head>
<body>
<h2>This is an example HTML page</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc
at nisi velit,
aliquet iaculis est. Curabitur porttitor nisi vel lacus euismo
d egestas. In hac
habitasse platea dictumst. In sagittis magna eu odio interdum
mollis. Phasellus
sagittis pulvinar facilisis. Donec vel odio volutpat tortor vo
lutpat commodo.
Donec vehicula vulputate sem, vel iaculis urna molestie eget.
Sed pellentesque
adipiscing tortor, at condimentum elit elementum sed. Mauris d
ignissim
elementum nunc, non elementum felis condimentum eu. In in turp
is quis erat
imperdiet vulputate. Pellentesque mauris turpis, dignissim sed
iaculis eu,
euismod eget ipsum. Vivamus mollis adipiscing viverra. Morbi a
t sem eget nisl
euismod porta.</p>
<p><a href="https://www.w3resource.com/html/HTML-
tutorials.php">Learn HTML from
w3resource.com</a></p>
<p><a href="https://www.w3resource.com/css/CSS-
tutorials.php">Learn CSS from
w3resource.com</a></p>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print("Number of paragraph tags:")
print(len(soup.find_all("p")))

OUTPUT:

Number of paragraph tags:


3

13.Write a Python program to add to a tag's contents in a given html document?


from bs4 import BeautifulSoup
html_doc = '<a href="http://example.com/">HTML<i>w3resource.co
m</i></a>'
soup = BeautifulSoup(html_doc, "lxml")
print("\nOriginal Markup:")
print(soup.a)
soup.a.append("CSS")
print("\nAfter appending a text in the new link:")
print(soup.a)

OUTPUT:
Original Markup:
<a href="http://example.com/">HTML<i>w3resource.com</i></a>

After appending a text in the new link:


<a href="http://example.com/">HTML<i>w3resource.com</i>CSS</a>

14. Write a Python program to create a new Arrow object, representing the "ceiling" of
the timespan of the Arrow object in a given timeframe using arrow module. The
timeframe can be any datetime property like day, hour, minute?

import arrow
print(arrow.utcnow())
print("Hour ceiling:")
print(arrow.utcnow().ceil('hour'))
print("\nMinute ceiling:")
print(arrow.utcnow().ceil('minute'))
print("\nSecond ceiling:")
print(arrow.utcnow().ceil('second'))

OUTPUT:

2019-06-01T11:08:59.961000+00:00
Hour ceiling:
2019-06-01T11:59:59.999999+00:00

Minute ceiling:
2019-06-01T11:08:59.999999+00:00

Second ceiling:
2019-06-01T11:08:59.999999+00:00

15.Write a Python program to create a new Arrow object, representing the "floor" of
the timespan of the Arrow object in a given timeframe using arrow module. The
timeframe can be any datetime property like day, hour, minute?

import arrow
print(arrow.utcnow())
print("Hour ceiling:")
print(arrow.utcnow().floor('hour'))
print("\nMinute ceiling:")
print(arrow.utcnow().floor('minute'))
print("\nSecond ceiling:")
print(arrow.utcnow().floor('second'))

OUTPUT:
2020-10-18T13:39:27.694413+00:00
Hour ceiling:
2020-10-18T13:00:00+00:00

Minute ceiling:
2020-10-18T13:39:00+00:00

Second ceiling:
2020-10-18T13:39:27+00:00

16.Write a Python program to create a time object with the same hour, minute, second,
microsecond and a timestamp representation of the Arrow object, in UTC time?

import arrow
a = arrow.utcnow()
print("Current datetime:")
print(a)
print("\nTime object with the same hour, minute, second, micro
second:")
print(arrow.utcnow().time())
print("\nTimestamp representation of the Arrow object, in UTC
time:")
print(arrow.utcnow().timestamp)

OUTPUT:

Current datetime:
2020-10-18T13:39:03.318821+00:00

Time object with the same hour, minute, second, microsecond:


13:39:03.324448

Timestamp representation of the Arrow object, in UTC time:


1603028343

17.Write a Python program to create and display a one-dimensional array-like object


containing an array of data using Pandas module?

import pandas as pd
a = pd.Series([2, 4, 6, 8, 10])
print(a)

OUTPUT:
0 2
1 4
2 6
3 8
4 10
dtype: int64

18.Write a Pandas program to compute the minimum, 25th percentile, median, 75th,
and maximum of a given series?
import pandas as pd
import numpy as np
num_state = np.random.RandomState(100)
num_series = pd.Series(num_state.normal(10, 4, 20))
print("Original Series:")
print(num_series)
result = np.percentile(num_series, q=[0, 25, 50, 75, 100])
print("\nMinimum, 25th percentile, median, 75th, and maximum o
f a given series:")
print(result)

OUTPUT:
Original Series:
0 3.000938
1 11.370722
2 14.612143
3 8.990256
4 13.925283
5 12.056875
6 10.884719
7 5.719827
8 9.242017
9 11.020006
10 8.167892
11 11.740654
12 7.665620
13 13.267388
14 12.690883
15 9.582355
16 7.874878
17 14.118931
18 8.247458
19 5.526727
dtype: float64

Minimum, 25th percentile, median, 75th, and maximum of a given


series:
[ 3.00093811 8.09463867 10.23353705 12.21537733 14.61214321]
19.Write a Pandas program to find the positions of numbers that are multiples of 5 of a
given series?

import pandas as pd
import numpy as np
num_series = pd.Series(np.random.randint(1, 10, 9))
print("Original Series:")
print(num_series)
result = np.argwhere(num_series % 5==0)
print("Positions of numbers that are multiples of 5:")
print(result)

OUTPUT:

Original Series:
0 1
1 9
2 8
3 6
4 9
5 7
6 1
7 1
8 1
dtype: int64
Positions of numbers that are multiples of 5:
[]

20.Write a Pandas program to get the day of month, day of year, week number and day
of week from a given series of date strings?

import pandas as pd
from dateutil.parser import parse
date_series = pd.Series(['01 Jan 2015', '10-02-2016',
'20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20'])
print("Original Series:")
print(date_series)
date_series = date_series.map(lambda x: parse(x))
print("Day of month:")
print(date_series.dt.day.tolist())
print("Day of year:")
print(date_series.dt.dayofyear.tolist())
print("Week number:")
print(date_series.dt.weekofyear.tolist())
print("Day of week:")
print(date_series.dt.weekday_name.tolist())

OUTPUT:
Original Series:
0 01 Jan 2015
1 10-02-2016
2 20180307
3 2014/05/06
4 2016-04-12
5 2019-04-06T11:20
dtype: object
Day of month:
[1, 2, 7, 6, 12, 6]
Day of year:
[1, 276, 66, 126, 103, 96]
Week number:
[1, 39, 10, 19, 15, 14]
Day of week:
['Thursday', 'Sunday', 'Wednesday', 'Tuesday', 'Tuesday', 'Sat
urday']

21.Write a Pandas program to create and display a DataFrame from a specified


dictionary data which has the index labels?

import pandas as pd
import numpy as np
exam_data = {'name': ['Venkat', 'Manikanta', 'Naga', 'Krishna
', 'Vamsi', 'Rakesh', 'Reddy', 'Yeswanth', 'Satish', 'Nikhil']
,'score': [23.6, 10, 27.6, np.nan, 10, 31, 25.6, np.nan, 9, 21
],'attempts': [2, 4, 3, 4, 3, 4, 2, 2, 3, 2],'qualify': ['yes'
, 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no','yes']}
labels = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
df = pd.DataFrame(exam_data , index=labels)
print(df)

OUTPUT:

S.NO Name score attempts qualify


1 Venkat 23.6 2 yes
2 Manikanta 10.0 4 no
3 Naga 27.6 3 yes
4 Krishna NaN 4 no
5 Vamsi 10.0 3 no
6 Rakesh 31.0 4 yes
7 Reddy 25.6 2 yes
8 Yeswanth NaN 2 no
9 Satish 9.0 3 no
10 Nikhil 21.0 2 yes
22.Write a Pandas program to display the first and last name and date of joining of the
employees who is either Sales Representative or Sales Man?

import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
employees = pd.read_csv(r"EMPLOYEES.csv")
departments = pd.read_csv(r"DEPARTMENTS.csv")
job_history = pd.read_csv(r"JOB_HISTORY.csv")
jobs = pd.read_csv(r"JOBS.csv")
countries = pd.read_csv(r"COUNTRIES.csv")
regions = pd.read_csv(r"REGIONS.csv")
locations = pd.read_csv(r"LOCATIONS.csv")

OUTPUT:
FIRST_NAME LAST_NAME HIRE_DATE
Krishna Vamsi 2020-10-18
Rakesh Reddy 2020-10-18

23.Write a Pandas program to display the first, last name, salary and department
number for those employees whose first name does not contain the letter 'M?

import pandas as pd

employees = pd.read_csv(r"EMPLOYEES.csv")

departments = pd.read_csv(r"DEPARTMENTS.csv")

job_history = pd.read_csv(r"JOB_HISTORY.csv")

jobs = pd.read_csv(r"JOBS.csv")

countries = pd.read_csv(r"COUNTRIES.csv")

regions = pd.read_csv(r"REGIONS.csv")

locations = pd.read_csv(r"LOCATIONS.csv")

print("First name Last name Salary Department


ID")

result = employees[employees['first_name'].str[-1]=='m']

for index, row in result.iterrows():


print(row['first_name'].ljust(15),row['last_name'].ljust(15),s
tr(row['salary']).ljust(9),row['department_id'])

OUTPUT:
First name Last name Salary Department ID
Venkat Vamsi 8200 50.0
Manikanta Rakesh 7900 50.0
Naga Reddy 7400 80.0
Krishna Yeswanth 8300 110.0

24.Write a Python program to draw line charts of the financial data of Alphabet Inc.
between July 22, 2020 to October 3, 2020?

import matplotlib.pyplot as plt


import pandas as pd
df = pd.read_csv('fdata.csv', sep=',', parse_dates=True,
index_col=0)
df.plot()
plt.show()

OUTPUT:

25. Write a Python program to display the grid and draw line charts of the closing value
of Alphabet Inc. between 22, 2020 to October 3, 2020 . Customized the grid lines with
rendering with a larger grid (major grid) and a smaller grid (minor grid).Turn on the
grid but turn off ticks?

import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
data = [(DT.datetime.strptime('2020-10-18', "%Y-%m-
%d"), 772.559998),(DT.datetime.strptime('2020-10-19', "%Y-
%m-%d"), 776.429993),(DT.datetime.strptime('2020-10-
20', "%Y-%m-%d"), 776.469971),(DT.datetime.strptime('2020-
10-21', "%Y-%m-
%d"), 776.859985),(DT.datetime.strptime('2020-10-22', "%Y-
%m-%d"), 775.080017 )]
x = [date2num(date) for (date, value) in data]
y = [value for (date, value) in data]
fig = plt.figure()
graph = fig.add_subplot(111)
# Plot the data as a red line with round markers
graph.plot(x,y,'r-o')
# Set the xtick locations
graph.set_xticks(x)
# Set the xtick labels
graph.set_xticklabels([date.strftime("%Y-%m-
%d") for (date, value) in data])
# naming the x axis
plt.xlabel('Date')
# naming the y axis
plt.ylabel('Closing Value')
# giving a title
plt.title('Closing stock value of Alphabet Inc.')
# Customize the grid
plt.grid(linestyle='-', linewidth='0.5', color='blue')
plt.show()

OUTPUT:

You might also like