NumPy Arrays
-
Learn how to create and use NumPy arrays for efficient data analysis in Python.
- One-Dimensional Arrays (1D Arrays)
A 1D array is a linear sequence of elements (like a list). All elements must be of the same data type.
Advantages over Python Lists:
Faster computation for large datasets
Uses less memory
Supports vectorized operations
Example – Creating a 1D Array
import numpy as np
# Creating a 1D array from a list
arr1D = np.array([10, 20, 30, 40, 50])
print("1D Array:", arr1D)
Output:
1D Array: [10 20 30 40 50]
1D Array Operations
Indexing: Access elements with arr1D[index]
print(arr1D[0]) # First element → 10
print(arr1D[-1]) # Last element → 50
Slicing: Extract multiple elements
print(arr1D[1:4]) # Elements from index 1 to 3 → [20 30 40]
print(arr1D[:3]) # First three elements → [10 20 30]
print(arr1D[2:]) # Elements from index 2 to end → [30 40 50]
Mathematical operations
arr2 = np.array([1,2,3,4,5])
print(arr1D + arr2) # [11 22 33 44 55]
print(arr1D * 2) # [20 40 60 80 100]
- Tips
Always prefer NumPy arrays over lists for numerical computations
Use vectorized operations instead of for-loops for performance
Two-Dimensional Arrays (2D Arrays)
A 2D array is a matrix-like structure with rows and columns. It is useful for tabular data, image data, or scientific computations.
Example – Creating a 2D Array
# 2 rows, 3 columns
arr2D = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", arr2D)
- Output:
2D Array:
[[1 2 3]
[4 5 6]]
2D Array Indexing
Access single element:
print(arr2D[0, 1]) # Row 0, Column 1 → 2
Access entire row:
print(arr2D[1, :]) # Row 1 → [4 5 6]
Access entire column:
print(arr2D[:, 2]) # Column 2 → [3 6]
2D Array Operations
mat1 = np.array([[1,2],[3,4]])
mat2 = np.array([[5,6],[7,8]])
print("Addition:\n", mat1 + mat2)
print("Multiplication:\n", mat1 * mat2) # Element-wise
print("Matrix Product:\n", np.dot(mat1, mat2)) # Matrix multiplication
- Tips
Use 2D arrays for tabular datasets, images, and matrices
Combine rows or columns using np.concatenate()
Reshape arrays with reshape() for better analysis
Array Creation Methods
NumPy provides flexible ways to create arrays:
1. From Python Lists
arr = np.array([1,2,3,4,5])
2. Zeros Array
zeros_arr = np.zeros((2,3))
Output:
[[0. 0. 0.]
[0. 0. 0.]]
3. Ones Array
ones_arr = np.ones((3,2))
- Output:
[[1. 1.]
[1. 1.]
[1. 1.]]
4. Using arange()
Generates sequences with a step value
arr = np.arange(0, 10, 2) # 0, 2, 4, 6, 8
5. Using linspace()
Generates evenly spaced numbers
arr = np.linspace(0, 1, 5) # 0, 0.25, 0.5, 0.75, 1
6. Random Arrays
rand_arr = np.random.rand(2,3) # Random floats [0,1)
rand_int = np.random.randint(1,10,5) # Random integers 1-9
7. Identity Matrix
id_matrix = np.eye(3)
- Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Summary – Array Creation