Array Reshaping and Array Iteration

NUMPY FUNDAMENTALS


Array Reshaping

Reshaping allows you to change the shape of an array without altering the data. Below is an example demonstrating how to reshape a NumPy array:


import numpy as np
arr = np.arange(12)  # Create an array with 12 elements
reshaped_arr = arr.reshape(3, 4)  # Reshape it into a 3x4 matrix

print("Original Array:", arr)
print("Reshaped Array:\n", reshaped_arr)
    
Tip: Use -1 to automatically infer one dimension.

auto_reshaped = arr.reshape(4, -1)  # NumPy automatically calculates the missing dimension
print(auto_reshaped.shape)  # Output: (4, 3)
    

Array Iteration

Iterating over arrays is a fundamental operation in NumPy. You can iterate over 1D and 2D arrays efficiently:

1. Iterating Over a 1D Array


arr_1d = np.array([10, 20, 30, 40])
for num in arr_1d:
    print(num)
    

2. Iterating Over a 2D Array

You can iterate over a 2D array row by row or element by element using np.nditer():


arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Iterating row by row
for row in arr_2d:
    print("Row:", row)

# Iterating element by element
for element in np.nditer(arr_2d):
    print("Element:", element)