Explanation of Python Code (NumPy Example)
Explanation
# NumPy
## 1.What is NumPy ,and why is it essential for numerical computations in python?
* NumPy is a powerful Python library used for numerical computing, it provides a powerful n-dimensional array
object (ndarray) that is more efficient than native python lists for numerical tasks.
##### Why its essential:
* Faster operations using vectorization.
* A wide range of mathematical function.
* Supports broadcasting , slicing and reshaping.
* Basis for many other libraries
Explanation
## 2.Create a 3x3 NumPy array filled with random integers between 1 and 10.Calculate the sum, mean,and standard
deviationof the array.
Code and Function Meanings
import numpy as np
# Create a 3x3 array with random integers feom 1 to 10
matrix = np.random.randint(1, 11, size=(3, 3))
print("Original 3x3 Matrix")
print(matrix)
# Calculate statistics
total = np.sum(matrix)
average = np.mean(matrix)
Explanation of Python Code (NumPy Example)
std_dev = np.std(matrix)
print("Sum:", total)
print("Mean:", average)
print("Standard Deviation:", std_dev)
Function Meanings:
- np.random: Generates random numbers.
- np.sum: Returns the sum of array elements.
- np.mean: Computes the average of array elements.
- np.std: Calculates standard deviation.
Explanation
## 3.Reshape the array into a 1x9 vector and display it.
Code and Function Meanings
import numpy as np
#Create a 3x3 matrix filled with random integers between 1 and 10
original_matrix = np.random.randint(1, 11, size=(3, 3))
#Display the original matrix
print("Original _Matrix (3x3):")
print(original_matrix)
#Reshape the matrix into a 1-row, 9-column matrix(1x9)
reshaped_matrix = original_matrix.reshape(1, 9)
#Display the reshaped matrix
Explanation of Python Code (NumPy Example)
print("Reshaped Matrix.reshape(1x9):")
print(reshaped_matrix)
Function Meanings:
- np.random: Generates random numbers.
Explanation
# Scipy
## 1.Discuss the main modules and their applications in scientific computing.
### i.scipy.integrate
* Used to calculate areas under curves and solve differential equations-helpful in physics and engineering for
modeling motion and population growth
### ii.scipy.optimize
* Solves optimization problems like finding minimum or maximum values-commonly used in machine
learning,economics and engineering design to improve performance or reduce cost.
### iii.scipy.linalg
* Handles advanced linear algebra tasks such as solving systems of equations-useful in simulations, data analysis,
and engineering computatios like circuit design.
### iv.scipy.stats
* Performs stastistical analysis, including probability distributions and tests-used in data science and research to
draw conclusions from data.
Explanation
# 2.Use scipy.optimize to find the minimum value of the function f(x)=x2+5x+6
Explanation of Python Code (NumPy Example)
Code and Function Meanings
from scipy.optimize import minimize
# Define the function to minimize
def func(x):
return x**2 + 5*x + 6
# Use minimize starting from x = 0
result = minimize(func, x0=[0])
print("Minimum value occurs at x =", result.x[0])
print("Minimum value of the function is:", result.fun)
Explanation
# 3.Plot the function using Matplolib to visualize the result
Code and Function Meanings
import matplotlib.pyplot as plt
# Create x values and compute y values
x_values = np.linspace(-10, 2, 100)
y_values = func(x_values)
# Plot the function
plt.plot(x_values, y_values, label='f(x)=x**2 + 5*x + 6', color='green')
plt.scatter(result.x, func(result.x), color='red', label='Minimum Point')
plt.title("Function Plot with Minimum")
plt.xlabel("x")
plt.ylabel("f(x)")
Explanation of Python Code (NumPy Example)
plt.legend()
plt.grid(True)
plt.show
Function Meanings:
- np.linspace: Creates evenly spaced numbers over a range.
Explanation
# Pandas
## 1.What are the two primary data structures in Pandas , and how do they differ?
* Series: 1D labeled array.
* DataFrame: 2D labeled data structure,like a table.
### Difference:
* Series is for single-column data, while DataFrame holds multiple columns and rows.
Explanation
# 2.Load a sample CSV file (or create a DataFrame manually) containing columns: Name, Age, Salary.
Code and Function Meanings
import pandas as pd
#Sample data
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Daisy'],
'Age': [28, 35, 28, 40],
'Salary': [55000, 48000, 60000, 75000]
}
Explanation of Python Code (NumPy Example)
df = pd.DataFrame(data)
print("DataFrame")
print(df)
Explanation
# 3.Filter rows where Salary > 50000
Code and Function Meanings
import pandas as pd
# Create a sample data as a dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Daisy'],
'Age': [28, 35, 28, 40],
'Salary': [55000, 48000, 60000,75000]
#Convert the dictionary into a Pandas DataFrame
df = pd.DataFrame(data)
#Display the full DataFrame
print("Full Employee Data:")
print(df)
#Filter rows where salary is greater than 50,000
high_salary_df = df[df['Salary'] > 50000]
#Display the filtered DataFrame
print("\nEmployees with Salary > 50000:")
print(high_salary_df)
Explanation of Python Code (NumPy Example)
Explanation
# 4.Group the data by Age and calculate the average salary for each age group.
Code and Function Meanings
import pandas as pd
#Create the sample employee data
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Daisy'],
'Age': [28, 35, 28, 40],
'Salary': [55000, 48000, 60000,75000]
#cCreate a DataFrame
df = pd.DataFrame(data)
#Display Full DataFrame
print("Full Employee Data:")
print(df)
# Group by 'Age' and calculate the average salary
average_salary_by_age = df.groupby('Age')['Salary'].mean()
# Display the result
print("\nAverage_Salary by Age Group:")
print(average_salary_by_age)
Explanation
# 5.Provide an example of how to handle missing values in a DataFrame using dropna() and fillna()
Explanation of Python Code (NumPy Example)
Code and Function Meanings
import pandas as pd
import numpy as np
data = {
'Name': ['David', 'Joel', 'Tamah', 'Zenekai'],
'Age': [25, 30, np.nan, 35],
'Salary': [60000, np.nan, 52000, 70000]
df =pd.DataFrame(data)
print("Original:\n", df)
#Drop rows with any missing values
print("\nAfter dropna():\n", df.dropna())
# Fill missing Age and Salary with their column averages
df_filled = df.copy()
df_filled['Age'] = df_filled['Age'].fillna(df_filled['Age'].mean())
df_filled['Salary'] = df_filled['Salary'].fillna(df_filled['Salary'].mean())
print("\nAfter fillna():\n", df_filled)
Explanation
# Matplotlib
## 1.What are the key features of Matplotlib that make it popular choice for creating plots?
* Flexible and powerful plotting library
* Works well with NumPy and Pandas
* Supports line,bar,pie,scatter,histograms and subplots
* Fully customizable(colors, styles and labels)
* Produces publication-quality visuals
Explanation of Python Code (NumPy Example)
## 2.Generate a line plot showing the population growth of the city of a city over 10 years .Add labels for the
x-axis(Years), Y-axis(population), and a title(City Population Growth).Customize the plot with gridlines, a legend, and a
specific color/style for the line.
Code and Function Meanings
import matplotlib.pyplot as plt
# Population Over 10 Years
years = list(range(2015, 2025))
population = [50000, 52000, 54000, 57000, 60000, 63000, 66000, 69000, 72000, 75000]
plt.plot(years, population,color='blue', linestyle='-', marker='o', label='Population')
plt.title("City Population Growth")
plt.xlabel("Years")
plt.ylabel("Population")
plt.grid(True)
plt.legend()
plt.show()
Explanation
# 2.Create a figure with two subplots: one displaying a bar chart of sales data and the other a pie chart showing market
share percentages.
Code and Function Meanings
import matplotlib.pyplot as plt
# Sales and market share data
sales = [100, 150, 500]
products = ['Product A', 'Product B', 'Product C']
Explanation of Python Code (NumPy Example)
market_share = [40, 35, 25]
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
#Bar Chart
axes[0].bar(products, sales, color='orange')
axes[0].set_title("Sales Data")
# Pie Chart
axes[1].pie(market_share, labels=products, autopct='%1.1f%%', colors=['skyblue', 'lightgreen', 'lightcoral'])
axes[1].set_title("Market Share")
plt.tight_layout()
plt.show()
Code and Function Meanings