NumPy provides several methods for creating arrays. These arrays are the foundation of numerical computations in NumPy, and their creation is versatile and efficient. Below is a detailed explanation of the various ways for Array Creation in NumPy.
1.) Creating Arrays from Python Lists or Tuples
- Arrays can be created directly from Python lists or tuples using
np.array()
.
import numpy as np
# From a list
arr1 = np.array([1, 2, 3, 4])
print(arr1)
# From a tuple
arr2 = np.array((5, 6, 7, 8))
print(arr2)
2.) Creating Arrays with Default Values
NumPy provides functions to create arrays initialized with default values like zeros, ones, or a specific constant.
a.) np.zeros()
- Creates an array filled with zeros.
arr = np.zeros((2, 3)) # 2x3 array of zeros
print(arr)
b.) np.ones()
- Creates an array filled with ones.
arr = np.ones((3, 2)) # 3x2 array of ones
print(arr)
c.) np.full()
- Creates an array filled with a specified value.
arr = np.full((2, 2), 7) # 2x2 array filled with 7
print(arr)
d.) np.empty()
- Creates an array without initializing its values (contains arbitrary values).
arr = np.empty((2, 2)) # 2x2 uninitialized array
print(arr)
Dimensions in NumPy:
In NumPy, dimension refers to the number of axes in an array, which is also known as the array’s rank.
- Arrays can have one or more dimensions, and their dimensionality determines their structure and how data is stored and accessed.
Understanding Dimensions
- 1D Array (1 Dimension): A single row or a single column of elements.
- 2D Array (2 Dimensions): A matrix with rows and columns.
- 3D Array (3 Dimensions): A collection of 2D arrays, like layers.
- nD Array (n Dimensions): An array with more than three dimensions.
NumPy Arrays by Dimension
a.) 1D Arrays
- Represented as a single list.
arr = np.array([10, 20, 30, 40])
print(arr)
b.) 2D Arrays
- Represented as a list of lists.
- Used for matrices.
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
c.) 3D Arrays
- Represented as a list of 2D arrays.
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr)