Menu
×
×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS NUMPY FOR ML Roadmap
     ❯   

NUMPY FUNDAMENTALS

Array Reshaping and Array Iteration

×

Share this Topic

Share Via:

Thank you for sharing!


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)
    

Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2025 Django-tutorial.dev .All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.