NumPy Tutorial NumPy Statistics NumPy Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

NumPy - Ndarray Object



Ndarray is the n-dimensional array object defined in the numpy. It stores the collection of elements of the same type. Elements in the collection can be accessed using a zero-based index. Each element in an ndarray takes the same size in memory.

Create a Numpy ndarray object

A Numpy ndarray object can be created using array() function. A list, tuple or any array-like object can be passed into the array() function to convert it into an ndarray. The syntax for using the function is given below:

Syntax

numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

Parameters

object Required. Specify the collection object to be converted into ndarray. It can be list, tuple, set, dictionary etc.
dtype Optional. Specify the desired data type. It is used to change the data type of the array element.
copy Optional. Specify True to copy the object, False otherwise.
order Optional. Specify order. It can take four possible values.
  • 'C' - for C order (row major).
  • 'F' - for F order (column major).
  • 'A' - unchanged if copy=False. If copy=True, F and C order preserved.
  • 'K' - unchanged if copy=False. If copy=True, When the input is F and not C then F order otherwise C order.
subok Optional. Specify True to make the returned array sub-classes pass through. By default, the returned array forced to be base class array.
ndmin Optional. Specify the minimum dimension of the array.

Example: Create 1-D Array

In the example below, a list is used to create a 1-D numpy array.

import numpy as np
MyList = [1, 2, 3, 4, 5]
npArray = np.array(MyList)
print(npArray)

The output of the above code will be:

[1 2 3 4 5]

Example: Create 2-D Array

In this example, a list of lists is used to create a 2-D numpy array.

import numpy as np
MyList = [[1, 2, 3], [4, 5, 6]]
npArray = np.array(MyList)
print(npArray)

The output of the above code will be:

[[1 2 3]
 [4 5 6]]

Example: Create 2-D Array using ndmin parameter

A n-dimensional array can be created using ndmin parameter of the array function. Like, in this example, it is used to create 2-D array.

import numpy as np
MyList = [1, 2, 3, 4, 5]
npArray = np.array(MyList, ndmin=2)
print(npArray)

The output of the above code will be:

[[1 2 3 4 5]]

Example: Create 1-D Array with dtype parameter

The dtype argument is used to change the data type of elements of the ndarray object.

import numpy as np
MyList = [1, 0, 0, 1, 0]
npArray = np.array(MyList, dtype=bool)
print(npArray)

The output of the above code will be:

[ True False False  True False]

5