NumPy ndarray
NumPy ndarray stands for n-dimensional array. This is a collection of homogenous “items” of the same “kinds”. The kind can be arbitrary data structure and is defined using data types.
Create an Array
We can import the package by using the import command and create an array,
We can use an alias to do the same, as
import numpy arr=numpy.array([[1,2,3,4],[5,6,7,8]],float) print(arr) # [[1. 2. 3. 4.] # [5. 6. 7. 8.]]
import numpy as np arr=np.array([[1,2,3,4],[5,6,7,8]],float) print(arr)
We can check the NumPy version,
import numpy as np print(np.__version__)
Getting the type
import numpy as np arr=np.array([[1,2,3,4],[5,6,7,8]],float) print(type(arr)) #Output #<class 'numpy.ndarray'>
Getting the shape and size of an array
import numpy as np arr=np.array([[1,2,3,4],[5,6,7,8]],float) print('Array shape {} and size {}'.format(arr.shape, arr.itemsize)) #Array shape (2, 4) and size 8
0-D array
A 0-D array is a scaler. Each value itself is an 0-D array in a multi-dimensional array. For example,
import numpy as np arr = np.array(45.8) print(arr)
1-D array
An array which is the collection of all scalers is a 1-D array. This is a unidirectional array.
import numpy as n arr = n.array(['Python','Java','PHP','JavaScript']) print(arr) #['Python' 'Java' 'PHP' 'JavaScript']
2-D array
An array that has 1-D arrays as its elements is known as a 2-D array. A 2-D array is used to represent matrix or second-order tensors. NumPy provides a specially dedicated submodule NumPy.mat for these arrays.
import numpy arr=numpy.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) print(arr) #[[ 1 2 3 4] #[ 5 6 7 8] #[ 9 10 11 12]]
3-D array
A 3-D array is a collection of 2-D arrays as its elements. 3-D arrays can be used to represent 3rd order tensors. For example,
import numpy as np arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) print(arr) #[[[10 12 13] # [ 6 7 11] # [ 4 2 7]] # [[ 0 9 7] # [ 4 15 2] # [ 9 6 3]]]
Getting and setting the dimension
import numpy as npy arr = npy.array([[[10, 12, 13], [6, 7, 11],[4,2,7]], [[0, 9, 7], [4, 15, 2],[9,6,3]]]) print(arr.ndim) # 3 Get the dim #We can also declare the number of dim #at the time of creation arnew=npy.array(['a','e','i','o','u'],ndmin=3) print(arnew.ndim) #3 Setting minimum dimension