This is the standard way to import Numpy into your Python project, and it's good practice.
import numpy as np
If modifying the array, ensure you make a copy of the array through
import numpy as np import copy arr = np.array([1,2,3]) a = copy.deepcopy(arr)
Make a multidimensional array
# 3D arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] result = np.array(arr) # 2D arr = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] result = np.array(arr) # 3D arr = [ [ [1,2], [3,4] ], [ [5,6], [7,8] ], [ [9,10], [11,12] ] ] result = np.array(arr)
Make a multidimensional array filled with something
# returns a 3x5 2D array filled with '.'s arr = np.full((3, 5), '.')
Get length of each side
np.size(array_name, axis_number) print('Axis 0 size : ', np.size(arr3D, 0)) print('Axis 1 size : ', np.size(arr3D, 1)) print('Axis 2 size : ', np.size(arr3D, 2))
1D Arrays can be accessed via indexing just like an array. 2D and higher use a slightly different syntax.
Axes are represented as (Y, X) in 2 dimensional arrays, as in (row, column).
# 2D arr = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] element = arr[0,0] # 1 element = arr[1,2] # 7
To iterate through every element within the array, going through all dimensions:
import numpy as np arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) for x in np.nditer(arr): print(x)
If you want indexes enumerated over also, as a tuple:
for index, x in np.ndenumerate(arr): print(index, x)
Last modified: 202107020543