Practicals Based on NumPy and Array

Practicals Based on NumPy and Array

Here's a practical example of using NumPy to perform operations on arrays. This program demonstrates matrix addition, multiplication, and finding the transpose of a matrix, which are common operations in various computational fields.

NumPy Array Operations: Practical Program
import numpy as np
# Function to print a matrix
def print_matrix(matrix, name):
    print(f"{name}:\n{matrix}\n")
# Initialize two matrices (2D arrays) using NumPy
matrix_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_b = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# Display the original matrices
print_matrix(matrix_a, "Matrix A")
print_matrix(matrix_b, "Matrix B")
# Matrix addition
matrix_sum = np.add(matrix_a, matrix_b)
print_matrix(matrix_sum, "Sum of A and B")
# Matrix multiplication (element-wise)
matrix_product = np.multiply(matrix_a, matrix_b)
print_matrix(matrix_product, "Element-wise Product of A and B")
# Matrix multiplication (dot product)
matrix_dot_product = np.dot(matrix_a, matrix_b)
print_matrix(matrix_dot_product, "Dot Product of A and B")
# Transpose of a matrix
matrix_a_transpose = np.transpose(matrix_a)
print_matrix(matrix_a_transpose, "Transpose of Matrix A")
# Creating a matrix with random values
random_matrix = np.random.randint(1, 10, size=(3, 3))
print_matrix(random_matrix, "Random Matrix")

Program Highlights
1. Matrix Addition: Adds corresponding elements of two matrices.
2. Element-wise Multiplication: Multiplies corresponding elements of two matrices.
3. Dot Product: A fundamental operation in linear algebra.
4. Transpose: Useful in data transformation and linear algebra.
5. Random Matrix: This shows how to generate random data using NumPy.

Sample Output
Matrix A:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Matrix B:
[[9 8 7]
 [6 5 4]
 [3 2 1]]

Sum of A and B:
[[10 10 10]
 [10 10 10]
 [10 10 10]]

Element-wise Product of A and B:
[[ 9 16 21]
 [24 25 24]
 [21 16  9]]

Dot Product of A and B:
[[ 30  24  18]
 [ 84  69  54]
 [138 114  90]]

Transpose of Matrix A:
[[1 4 7]
 [2 5 8]
 [3 6 9]]

Random Matrix:
[[6 1 3]
 [4 7 2]
 [5 9 8]]

This program is useful for learning basic matrix operations in NumPy, a core skill for data analysis, machine learning, and scientific computing.

Here's a Python program that uses NumPy to analyze weekly temperature data. The program computes the average, maximum, and minimum and identifies days with temperatures above the weekly average.

Weekly Temperature Analysis

import numpy as np
# Input: Temperature data for 7 days (in Celsius)
temperatures = np.array([28, 32, 30, 31, 29, 35, 33])
# Display the temperature data
print(f"Temperature data (°C): {temperatures}")
# Calculate the average temperature
average_temp = np.mean(temperatures)
print(f"Average temperature of the week: {average_temp:.2f}°C")
# Find the maximum temperature
max_temp = np.max(temperatures)
max_day = np.argmax(temperatures) + 1 # +1 because array index starts at 0
print(f"Maximum temperature: {max_temp}°C (Day {max_day})")
# Find the minimum temperature
min_temp = np.min(temperatures)
min_day = np.argmin(temperatures) + 1
print(f"Minimum temperature: {min_temp}°C (Day {min_day})")
# Identify days with temperatures above the average
above_avg_days = np.where(temperatures > average_temp)[0] + 1
above_avg_temps = temperatures[temperatures > average_temp]
print(f"Days with temperatures above average: {above_avg_days}")
print(f"Corresponding temperatures: {above_avg_temps}")
# Additional Insights: Sort the temperatures
sorted_temps = np.sort(temperatures)
print(f"Sorted temperatures: {sorted_temps}")
# Visualization (Optional - Requires Matplotlib)
try:
import matplotlib.pyplot as plt
days = np.arange(1, 8) # Days of the week
plt.plot(days, temperatures, marker='o', label='Temperature')
plt.axhline(y=average_temp, color='r', linestyle='--', label='Average Temp')
plt.xticks(days)
plt.xlabel("Day of the Week")
plt.ylabel("Temperature (°C)")
plt.title("Weekly Temperature Data")
plt.legend()
plt.grid(True)
plt.show()
except ImportError:
print("Matplotlib not installed. Skipping visualization.")

Program Highlights

  1. Input Data: Stores temperatures in a NumPy array for efficient computation.
  2. Statistics:
    • Computes average, maximum, and minimum temperatures.
    • Identifies the day of the maximum/minimum temperature.
  3. Above Average Analysis: Lists days and temperatures above the weekly average.
  4. Sorting: Sorts temperature data for trend analysis.
  5. Visualization: (Optional) Uses Matplotlib to graph the temperature trends.

Sample Output

Temperature data (°C): [28 32 30 31 29 35 33]
Average temperature of the week: 31.14°C
Maximum temperature: 35°C (Day 6)
Minimum temperature: 28°C (Day 1)
Days with temperatures above average: [2 4 6 7]
Corresponding temperatures: [32 31 35 33]
Sorted temperatures: [28 29 30 31 32 33 35]

Visualization

The visualization (if Matplotlib is installed) shows:

  • A line graph of temperatures over the week.
  • The weekly average temperature as a dashed horizontal line.


This program is great for understanding how to use NumPy for statistical analysis and how to optionally visualize data trends with Matplotlib.

Comments