What is Computer

Module: M2-R5: Web Design & Publishing

Chapter: Ch1 Computer Intro

🔹 What is an ndarray?

In NumPy, the core data structure is the ndarray (N-dimensional array). It is a grid of values (of the same type) indexed by a tuple of nonnegative integers. NumPy arrays are faster, more compact, and more convenient than traditional Python lists for numerical computations.

💡 Why Use ndarray?
  • Efficient memory usage
  • Supports element-wise operations
  • Allows slicing, indexing, reshaping, and broadcasting
  • Can handle large datasets efficiently
🔹 Creating ndarrays
import numpy as np

# From a Python list
arr1 = np.array([1, 2, 3, 4])
print("1D Array:", arr1)

# From a list of lists (2D array)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", arr2)

# Using functions
arr3 = np.zeros((2, 3))    # 2x3 array of zeros
arr4 = np.ones((3, 2))     # 3x2 array of ones
arr5 = np.arange(0, 10, 2) # Even numbers from 0 to 8
arr6 = np.linspace(0, 1, 5) # 5 evenly spaced values
🔹 ndarray Attributes
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])

print("Shape:", arr.shape)   # (2, 3)
print("Dimensions:", arr.ndim) # 2
print("Size:", arr.size)     # 6
print("Data type:", arr.dtype)
print("Item size (bytes):", arr.itemsize)
print("Total bytes:", arr.nbytes)

Output:

Shape: (2, 3)
Dimensions: 2
Size: 6
Data type: int64
Item size (bytes): 8
Total bytes: 48
🔹 Accessing Elements in ndarray
import numpy as np
arr = np.array([[10, 20, 30], [40, 50, 60]])

print(arr[0, 1])  # 20
print(arr[1, -1]) # 60
🔹 Slicing in ndarray
arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])   # [20 30 40]

arr2 = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr2[0:2, 1:3])  # [[2 3] [5 6]]
🔹 Reshaping Arrays
arr = np.arange(1, 9)
reshaped = arr.reshape((2, 4))
print(reshaped)

Output:

[[1 2 3 4]
 [5 6 7 8]]
🔹 Operations on ndarrays
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print(a + b)  # [5 7 9]
print(a * b)  # [4 10 18]
print(a ** 2) # [1 4 9]
✅ Summary
  • ndarray is the main container for numerical data in NumPy.
  • It supports vectorized operations for fast computation.
  • Attributes like shape, ndim, dtype help describe the array.
  • Can be reshaped, sliced, and broadcasted easily.
Quick Links