Dimensions and Shapes of Numpy Arrays (Basics)
Arrays are fundamental data structures in programming that allow us to store and manipulate collections of values. Understanding array dimensions and shapes is crucial when working with multi-dimensional arrays.
Array Dimensions
An array's dimension refers to the number of indices required to access an element within the array. In simple words, it tells us how many axes an array have.
1D Array
A one-dimensional array is the simplest form of an array. It is a linear collection of elements. It is similar to python lists.
Example
# Creating a one-dimensional array
OneD_array = [1, 2, 3, 4, 5]
2D Array
A two-dimensional array is like a grid or matrix. It has rows and columns, and we can access elements using these rows and columns.
Example
# Creating a two-dimensional array
TwoD_array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Multi-dimensional Array
Arrays can have more than two dimensions, and they are known as multi-dimensional arrays. These are often used in scientific computing and image processing.
Example
# Creating a three-dimensional array
import numpy as np
ThreeD = np.array([
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
])
Arrays Indexing
Accessing an array is done via indexing. One can access an array element by using its index number. The Index starts with 0 all the way to the (n - 1) where n is the length of the array
i.e. 0th index is the first element and 1st index is the second element and so on and the last element has the index (n - 1).
Example
import numpy as np
arr = np.array([2,-8,4,55,10,32,-76])
print(arr[0]) # prints 2
print(arr[1]) # prints -8
print(arr[6]) # prints -76
Array Shapes
The shape of an array is represented as a tuple, where each element of the tuple represent the size of a dimension.
Example
import numpy as np
arr = np.array([
[1, 2, 3],
[4, 5, 6]
])
shape = arr.shape # Output (2, 3)