Python Assignment (Sem 2) MBA
Python Assignment (Sem 2) MBA
SEMESTER-II
ACADEMIC YEAR: 2023-2024
Time_min = 42
Time_sec = 42
New_Time_sec = Time_min * 60 + Time_sec
print(New_Time_sec)
OUTPUT:
#While Loop:-
n=int(input("Enter any number"))
i=1
while i<11:
print(n,"x",i,"=",n*i)
i=i+1
OUTPUT:
OUTPUT:
char = char.lower()
print("The lowercase character is:", char)
else:
print("Invalid input!")
OUTPUT:
8. WAP to enter the marks of a student in 4 subjects. Calculate total and average
and display the division obtained by the student.
CODE:
a=int(input("Enter physics marks:\n"))
b=int(input("Enter hindi marks:\n"))
c=int(input("Enter english marks:\n"))
d=int(input("Enter math marks:\n"))
total=a+b+c+d
print("The total of marks is "+str(total))
avg=a+b+c+d
print("The total of marks is "+str(avg))
percent=(total/400)*100
if(percent>=60):
print("First Division")
elif(percent>50 and percent<59.9):
print("Second division")
elif(percent>33 and percent<49.9):
print("Third Division")
else:
print("pass")
OUTPUT:
6
9.Write a program in python for a user define function diff which is use to
function diff num?
CODE:
def diff(num1, num2):
# calculate the absolute difference between num1 and num2
diff = abs(num1 - num2)
# return the result
return diff
# example usage
result = diff(10, 7)
print("The absolute difference between 10 and 7 is:", result)
OUTPUT:
10.Write a program to count the numbers of characters in the given string and store them in a
dictionary data structure?
CODE:# take input string from user
string = input("Enter a string: ")
# initialize an empty dictionary
char_count = {}
7
11.Write a program to use split and join methods in the given string and trace a birthday
with a dictionary data structure.
CODE:
# take input string from user
string = input("Enter a name and birthday (MM/DD/YYYY) separated by a space: ")
# split the string into name and birthday
name, birthday = string.split()
# create a dictionary with the name and birthday
birthday_dict = {name: birthday}
# print the dictionary
8
print(birthday_dict)
# convert the dictionary to a string using join
birthday_str = " ".join([f"{name}: {birthday}" for name, birthday in birthday_dict.items()])
# print the string
print(birthday_str)
OUTPUT:
b.
9
14. Write a function unique to find all the unique elements of a list.
CODE:
def unique(lst):
"""
Find all unique elements in a list.
"""
seen = set()
unique_items = [ ]
10
writer = csv.writer(file)
reader = csv.reader(file)
header = next(reader)
# Print header
print(header)
print(row)
OUTPUT:
numbers = [1, 2, 3, 4, 5]
print(list(squares))
OUTPUT:
12
CODE: b.
print(list(sums))
OUTPUT:
OUTPUT:
14
print("Sum_of_elements:",sum_of_elements)
import numpy as np
in_num1 = 10
in_num2 = 11
16
OUTPUT:
22. Write a Pandas program to create and display a one-dimensional array-like object
containing an array of data using Pandas module.
CODE:
import pandas as pd
17
23. Write a Pandas program to add, subtract, multiple and divide two Pandas Series.
Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9].
CODE:
import pandas as pd
# Create two Series
series1 = pd.Series([2, 4, 6, 8, 10])
series2 = pd.Series([1, 3, 5, 7, 9])
24. Write a Pandas program to get the powers of an array values element-wise. Note: First
array elements raised to powers from second array
Sample data: {'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]}
CODE:
import pandas as pd
df = pd.DataFrame(data)
print(df)
print("Powers:",powers)
OUTPUT:
25. Write a Pandas program to create and display a DataFrame from a specified dictionary
data which has the index labels.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'].
20
CODE:
import pandas as pd
import numpy as np
26. Write a Pandas program to get the first 3 rows of a given DataFrame.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CODE:
import pandas as pd
import numpy as np
27. Write a Pandas program to select the 'name' and 'score' columns from the following
DataFrame. Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CODE:
import pandas as pd
import numpy as np
28. Write a Pandas program to select the rows where the number of attempts in the
examination is greater than 2.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CODE:
import pandas as pd
import numpy as np
29. Write a Pandas program to count the number of rows and columns of a DataFrame.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
CODE:
import pandas as pd
import numpy as np
'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin',
'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']
}
OUTPUT:
30. Write a Pandas program to sort the DataFrame first by 'name' in descending order, then
by 'score' in ascending order.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
26
# Sort the DataFrame by 'name' in descending order and 'score' in ascending order
sorted_df = df.sort_values(by=['name', 'score'], ascending=[False, True])
OUTPUT:
31. Write a Pandas program to create a dataframe and set a title or name of the index
column.
CODE:
import pandas as pd
# Create a DataFrame
data = {
'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']
}
df = pd.DataFrame(data)
32. Write a Pandas program to join the two given dataframes along rows and assign all data.
CODE:
import pandas as pd
# Create the first DataFrame
data1 = {
'Name' : ['ana', 'andy', 'samara'],
'Age' : [20, 22, 34],
'City' : ['Newyork', 'London', 'Paris']
}
df1 = pd.DataFrame(data1)
data2 = {
'Name' : ['Akanksha', 'Dhruva', 'Rajeev'],
'Age' : [15, 20, 25],
'City' : ['chicago', 'Berlin', 'Tokyo']
}
df2 = pd.DataFrame(data2)
# Join the two DataFrames along rows and assign all data
joined_df = pd.concat([ df1, df2 ])
# Display the joined DataFrame
print(joined_df)
OUTPUT:
29
33. Write a Pandas program to append rows to an existing DataFrame and display the
combined data.
CODE:
import pandas as pd
# Create the first DataFrame
data1 = {
'Name' : ['ana', 'andy', 'samara'],
'Age' : [20, 22, 34],
'City' : ['Newyork', 'London', 'Paris']
}
df1 = pd.DataFrame(data1)
data2 = {
'Name' : ['Akanksha', 'Dhruva', 'Rajeev'],
'Age' : [15, 20, 25],
'City' : ['chicago', 'Berlin', 'Tokyo']
}
df2 = pd.DataFrame(data2)
# Append the new data to the existing DataFrame
combined_df = df.append(df2)
# Display the joined DataFrame
print(combined_df)
OUTPUT:
30
34. Write a Pandas program to append a list of dictioneries or series to a existing DataFrame
and display the combined data.
CODE:
import pandas as pd
# e) Current date
33
current_date = pd.to_datetime('today').date()
37. Write a Pandas program to create a date from a given year, month, day and another date
from a given string formats.
CODE:
import pandas as pd
from datetime import datetime
OUTPUT
36
38. Write a Pandas program to print the day after and before a specified date. Also print the
days between two given dates.
CODE:
import pandas as pd
OUTPUT:
40. Write a Pandas program to get the current date, oldest date and number of days between
Current date and oldest date of Ufo dataset.
CODE:-
Code:
import pandas as pd
# Sample data for demonstration
38
data = {
'Date': pd.to_datetime(['2023-07-21', '2022-12-15', '2020-04-10', '2019-08-25'])
}
ufo_df = pd.DataFrame(data)
# Get the current date
current_date = pd.to_datetime('today').date()
# Get the oldest date in the 'Date' column of the DataFrame
oldest_date = ufo_df['Date'].min().date()
# Calculate the number of days between the current date and the oldest date
days_difference = (current_date - oldest_date).days
print("Current Date:", current_date)
print("Oldest Date:", oldest_date)
print("Number of Days between Current Date and Oldest Date:", days_difference)
OUTPUT:-
OUTPUT
42. Write a Pandas program to create a line plot of the historical stock prices of Alphabet Inc.
between two specific dates
CODE:-
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
43.Write a Pandas program to create a bar plot of the trading volume of Alphabet Inc. stock
between two specific dates
CODE:-
pip install yfinance
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
41
except Exception as e:
print("Error:", e)
if __name__ == "__main__":
symbol = "GOOG" # Stock symbol for Alphabet Inc.
start_date = "2023-01-01"
end_date = "2023-07-20"
plot_trading_volume(symbol, start_date, end_date)
OUTPUT:-
42
44. Write a Pandas program to create a histograms plot of opening, closing, high, low stock
prices of Alphabet Inc. between two specific dates.
CODE:-
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Call the function with the stock symbol of Alphabet Inc. (GOOGL)
plot_stock_histogram('GOOGL', start_date, end_date)
OUTPUT:-
44
45. Write a python program to demonstrate use of matplotlib to display bar graph,
histogram, scatter plot, area plot, pie plot.
CODE
import matplotlib.pyplot as plt
# Bar Graph
plt.figure(figsize=(8, 4))
plt.bar(x, y, label='Bar Graph')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Bar Graph Example')
plt.legend()
plt.show()
# Histogram
plt.figure(figsize=(8, 4))
plt.hist(data, bins=5, rwidth=0.8, alpha=0.7, color='blue')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram Example')
plt.show()
45
# Scatter Plot
plt.figure(figsize=(8, 4))
plt.scatter(x, y, label='Scatter Plot', color='red', marker='o', s=100)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
plt.legend()
plt.show()
# Area Plot
plt.figure(figsize=(8, 4))
plt.stackplot(x, y, labels=['Area Plot'], alpha=0.7)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Area Plot Example')
plt.legend()
plt.show()
# Pie Plot
labels = ['A', 'B', 'C', 'D', 'E']
plt.figure(figsize=(8, 8))
plt.pie(data, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
plt.title('Pie Plot Example')
plt.show()
OUTPUT
46
47
OUTPUT
50
data = pd.read_csv('C:\\Users\\tgeor\\Downloads\\customer_data.csv')
data.head()
print(data.columns)
OUPUT
print(X)
OUTPUT
y = data.loc[:,['purchase_made']] # Labels
print(y)
OUTPUT
53
# Split the data into training and testing sets; 20% data is used to test and 8
print(X_train)
print(X_test)
print(y_train)
print(y_test)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
print(y_pred)
print("Accuracy:", accuracy)
54
OUPUT