Numpy

Numpy is a Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. Numpy is the foundation of many other Python libraries for scientific computing, such as Pandas, Scipy, and Matplotlib.

In this section, we will cover the basics of Numpy, including how to create arrays, perform mathematical operations, and manipulate array data.

Creating Arrays

Array Properties

Indexing and Slicing

Modifying Arrays

Mathematical Operations

Matrix Operations

Aggregation Functions

Reshaping and Stacking

Boolean Masking

Broadcasting

Exercise

Complete the following tasks using NumPy based on what you’ve learned:

  1. Create a 4x4 NumPy array with random integers between 1 and 100.
  2. Replace all even numbers in the array with -1.
  3. Compute the sum of each row and store it in a new array.
  4. Reshape the original 4x4 array into a 2x8 array.
  5. Find the maximum value in the reshaped array.
import numpy as np

# Step 1: Create a 4x4 array with random integers between 1 and 100
arr = np.random.randint(1, 101, (4, 4))
print("Original Array:\n", arr)

# Step 2: Replace even numbers with -1
arr[arr % 2 == 0] = -1
print("Modified Array:\n", arr)

# Step 3: Compute row-wise sum
row_sums = np.sum(arr, axis=1)
print("Row sums:", row_sums)

# Step 4: Reshape into 2x8
reshaped_arr = arr.reshape(2, 8)
print("Reshaped Array:\n", reshaped_arr)

# Step 5: Find maximum value in reshaped array
max_value = np.max(reshaped_arr)
print("Maximum value:", max_value)