Python Lab Assignment 7
Topics Covered: NumPy, Pandas, Matplotlib
1. Plot of y = x^2
Problem:
Plot a graph of y = x^2 for x values from 0 to 10.
Customize the graph with the following features:
- Set the title as "Quadratic Function"
- Label the x-axis as "x" and the y-axis as "y"
- Change the line color to red and line style to dashed.
Code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 11, 1)
y = x**2
plt.plot(x, y, 'r--')
plt.title('Quadratic Function')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
2. Bar Chart of Student Scores
Problem:
Given the list of students' names ["Alice", "Bob", "Charlie", "David"] and their corresponding scores [85, 92,
78, 90],
plot a bar chart to represent the scores of each student.
Code:
import matplotlib.pyplot as plt
students = ['Alice', 'Bob', 'Charlie', 'David']
scores = [85, 92, 78, 90]
plt.bar(students, scores, color='blue')
plt.title('Student Scores')
plt.xlabel('Students')
plt.ylabel('Scores')
plt.show()
3. Scatter Plot of Random Data Points
Problem:
Write a Python program that generates random x and y data points using NumPy and creates a scatter plot
using Matplotlib.
Code:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
plt.scatter(x, y, color='green')
plt.title('Scatter Plot of Random Data Points')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()
4. Multiplication of Two 3x3 Matrices
Problem:
Write a Python program that multiplies two 3x3 matrices using NumPy's dot() function.
Code:
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result = np.dot(A, B)
print('Result of Matrix Multiplication:')
print(result)
5. Slicing a NumPy Array
Problem:
Create a NumPy array with numbers from 1 to 20 and slice the array to print:
- The first 5 elements
- The last 5 elements
- Elements at even indices
Code:
import numpy as np
arr = np.arange(1, 21)
print('First 5 elements:', arr[:5])
print('Last 5 elements:', arr[-5:])
print('Elements at even indices:', arr[1::2])
6. Element-wise Operations on NumPy Arrays
Problem:
Create two NumPy arrays a = np.array([1, 2, 3]) and b = np.array([4, 5, 6]).
Perform element-wise addition, subtraction, multiplication, and division of these arrays and print the results.
Code:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print('Addition:', a + b)
print('Subtraction:', a - b)
print('Multiplication:', a * b)
print('Division:', a / b)
7. Statistical Calculations on a NumPy Array
Problem:
Given a NumPy array data = np.array([10, 15, 7, 22, 17]), calculate and print the following statistics:
- Mean
- Standard deviation
- Median
- Sum of all elements
Code:
import numpy as np
data = np.array([10, 15, 7, 22, 17])
print('Mean:', np.mean(data))
print('Standard Deviation:', np.std(data))
print('Median:', np.median(data))
print('Sum of All Elements:', np.sum(data))
8. DataFrame Operations
Problem:
Create a DataFrame with the following data:
data = {"Name": ["John", "Anna", "Peter", "Linda"],
"Age": [28, 24, 35, 32],
"City": ["New York", "London", "Berlin", "Tokyo"]}
Perform the following operations:
- Print the column "Age"
- Add a new column "Salary" with values [50000, 60000, 55000, 65000]
- Filter and display rows where the "Age" is greater than 30
Code:
import pandas as pd
data = {"Name": ["John", "Anna", "Peter", "Linda"],
"Age": [28, 24, 35, 32],
"City": ["New York", "London", "Berlin", "Tokyo"]}
df = pd.DataFrame(data)
print('Age column:')
print(df['Age'])
df['Salary'] = [50000, 60000, 55000, 65000]
print('Rows where Age > 30:')
print(df[df['Age'] > 30])
9. Merging Two DataFrames
Problem:
Write a Python program to merge two DataFrames using Pandas.
One DataFrame contains employee details (ID, Name, Department),
and another contains employee salaries (ID, Salary).
Merge them based on the "ID" column.
Code:
import pandas as pd
df1 = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie'], 'Department': ['HR', 'IT', 'Finance']})
df2 = pd.DataFrame({'ID': [1, 2, 3], 'Salary': [50000, 60000, 70000]})
merged_df = pd.merge(df1, df2, on='ID')
print(merged_df)
10. Weather Data Analysis using Pandas
Problem:
Read a CSV file containing daily weather data (e.g., temperature, humidity, rainfall).
Use Pandas to perform the following:
- Calculate the average temperature for each month
- Plot a line graph of the daily temperature over time using Matplotlib.
Code:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('weather_data.csv')
monthly_avg_temp = df.groupby(df['Date'].str[:7])['Temperature'].mean()
print('Monthly Average Temperature:')
print(monthly_avg_temp)
plt.plot(df['Date'], df['Temperature'])
plt.title('Daily Temperature Over Time')
plt.xlabel('Date')
plt.ylabel('Temperature')
plt.xticks(rotation=45)
plt.show()