Arrays in Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[2])
print(type(arr))
3
<class 'numpy.ndarray'>
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
[1 2 3 4 5]
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D
array.
import numpy as np
arr = np.array([42,1,2,3,4,5])
print(arr)
print(arr.ndim)
[42 1 2 3 4 5]
1
Arrays in Python 1
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
import numpy as np
arr = np.array([[[1, 2, 3, 4, 5]]])
print(arr)
print(arr.ndim)
[[[1 2 3 4 5]]]
3
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array. These are often
used to represent matrix
import numpy as np
arr = np.array([[[1, 2, 3],[4, 5, 6],[3,4,5]]])
print(arr)
print(arr.ndim)
[[[1 2 3]
[4 5 6]
[3 4 5]]]
3
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
import numpy as np
arr = np.array([[[1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8, 9]], [[1, 2, 3, 4, 5 ,6], [4, 5,
6, 7, 8, 9]]])
print(arr[0][1])
print(arr)
print(arr.ndim)
Arrays in Python 2
[4 5 6 7 8 9]
[[[1 2 3 4 5 6]
[4 5 6 7 8 9]]
[[1 2 3 4 5 6]
[4 5 6 7 8 9]]]
3
Check Number of Dimensions
import numpy as np1
a = np1.array(42)
b = np1.array([1, 2, 3, 4, 5])
c = np1.array([[1, 2, 3], [4, 5, 6]])
d = np1.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
0
1
2
3
Higher Dimensional Arrays
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
[[[[[1 2 3 4]]]]]
number of dimensions : 5
Arrays in Python 3