Module: M4-R5: Internet of Things (IoT)
Chapter: Ch1 Computer Intro
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.
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
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
import numpy as np
arr = np.array([[10, 20, 30], [40, 50, 60]])
print(arr[0, 1]) # 20
print(arr[1, -1]) # 60
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]]
arr = np.arange(1, 9)
reshaped = arr.reshape((2, 4))
print(reshaped)
Output:
[[1 2 3 4]
[5 6 7 8]]
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]
shape, ndim, dtype help describe the array.