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:
- Create a 4x4 NumPy array with random integers between 1 and 100.
- Replace all even numbers in the array with -1.
- Compute the sum of each row and store it in a new array.
- Reshape the original 4x4 array into a 2x8 array.
- 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
= np.random.randint(1, 101, (4, 4))
arr print("Original Array:\n", arr)
# Step 2: Replace even numbers with -1
% 2 == 0] = -1
arr[arr print("Modified Array:\n", arr)
# Step 3: Compute row-wise sum
= np.sum(arr, axis=1)
row_sums print("Row sums:", row_sums)
# Step 4: Reshape into 2x8
= arr.reshape(2, 8)
reshaped_arr print("Reshaped Array:\n", reshaped_arr)
# Step 5: Find maximum value in reshaped array
= np.max(reshaped_arr)
max_value print("Maximum value:", max_value)