In this tutorial, we are going to learn about ndarray in numpy and how to construct one. We will also learn about the syntax of an nd array and how to find out shape, type and data type of it.

What is ndarray?

ndarray is an array class in Numpy, it is also known as array. It is not as same the array.array that we use in Python because that only handles a single dimensional array and have limited functionality. Array object consists of a multidimensional array of fixed-size items. Arrays is a list of elements i.e. numbers of the same data type.

You can access the elements present in Numpy by using square [ ] brackets. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists. You can find out about the number of dimensions of an array through its shape. The common syntax of declaring a numpy array is:

array_name = module_name.array( [ list of numbers ] )

The number of dimensions and items in an array is defined by its shape, which is a tuple of N positive integers that specify the sizes of each dimension. For example, let’s construct a 2-dimensional array of 2×2. First import numpy in your python editor:

import numpy as np
arr = np.array([[ 1, 2],
      [ 4, 2]])

Think of 2-D arrays as matrices that has rows into columns (r x c), you can always specify the rows and columns of an array by utilizing the shape method, similarly you can find the type and data type of the array as well by using the type and data type methods:

import numpy as np arr = np.array([[ 1, 2], [ 4, 2]]) print(arr) #Shape of an array print("Shape of an array is: " , arr.shape) #Type of an array print("Type of an array is: ", type(arr)) #Datatype of an array print("Data type of an array: ", arr.dtype)