ndarray- An n-dimensional array of homogeneous data types

n-dimensional array ndarray.ndim and Axes

The dimension of an array refers to the number of axes (or dimensions) in the array.

n-dimensional array ndarray object has many attributes (discussed in the next section).  One of these attributes is ndim (ndarray.ndim).

ndim attribute specifies the number of axes (dimensions) of the array. Each axis corresponds to a dimension in the array and is associated with a specific dimension of the array.

What are Axes in NumPy

Below are the axes of different NumPy arrays:

1D Array: A 1-D Array is a list of numbers.  It has one axis.

Example 1: an array of shape (4,) has one axis with four elements. Example 2: an array of shape (3,) has one axis with three elements

Note: The shape attribute is discussed in later in this page.

A 2-D Array is a matrix of rows and columns. It has 2 axes.

For example, an array of shape (3, 4) has:

  • Axis 0: Rows (3 elements)
  • Axis 1: Columns (4 elements)

More information on Axes is at the link below:

https://numpy.org/doc/stable/glossary.html#term-axis

3-D Array: A 3-D array is a matrix of matrices. It has 3 axes. (Imagine a 3-D array as a cube with array elements along the x, y, and z co-ordinates).

For example, an array of shape (2, 3, 4) has:

  • Axis 0: Depth (2 elements)
  • Axis 1: Rows (3 elements)
  • Axis 2: Columns (4 elements)

The Table below relates the array’s dimension to its axis.

Table of Axes for Different Types of Arrays

Type of ArrayDescriptionExampleShapeAxes Count
ScalarSingle valuenp.array(5)()0
1D ArrayOne-dimensional array A list of numbersnp.array([1, 2, 3])(3,)1
2D ArrayTwo-dimensional array (matrix with rows and columns)np.array([[1, 2], [3, 4]])(2, 2)2
3D ArrayThree-dimensional array (collection of matrices)np.array([[[1], [2]], [[3], [4]]])(2, 2, 1)3

Overview of ndarray Attributes

NumPy’s ndarray (n-dimensional array) has several key attributes that provide important information about the structure of arrays, such as their dimensions, shape, data type and size, which are crucial for understanding and manipulating data effectively.

Key Attributes

AttributeDescription
ndarray.ndimndim: the number of axes (dimensions) of the array. (see table below). ndim tells us the dimensionality of the NumPy array. The number of dimensions can be thought of as the number of distinct “axes”.
ndarray.shapeAttribute shape returns a tuple containing the number of elements in each dimension.
shape is a tuple of integers indicating the size of the array in each dimension. For a 2-D arrow with n rows and m columns, the shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.
A tuple representing the size of each dimension. For example, a shape of (3, 4) indicates 3 rows and 4 columns. (See table below).
ndarray.sizesize tells us the  total number of elements of the array. This is equal to the product of the elements of shape ( n*m).  The total number of elements in the array is calculated as the product of the sizes of all dimensions. See table below.
ndarray.dtypedtype object describes the type of the elements in the array, which defines the type of data stored (e.g., integers, floats).

For details of ndarray attributes, click on the link below.

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html

NumPy provides several dtypes, in addition to the ones in Python. You can create arrays by specifying standard Python dtypes or the NumPy dtypes.

Some of NumPy dtypes are listed below:

  • numpy.int32
  • numpy.int16
  • numpy.float64

ndarray.itemsize

Attribute itemsize is the size of each element of the array in bytes.

For example, type numpy.float64 element has itemsize 8 (=64/8), while the  type numpy.complex32 has itemsize 4 (=32/8).

It is equivalent to ndarray.dtype.itemsize.

The table below shows details of ndim Attributes:

n-dimensional array Attributes

Array TypeArray Example# of Axisndim# of Elements Array.sizeshape
ScalarSingle value np.array(5)00 ()
1-D Array[1 2 6 8]114(4,)
2-D Array[[1 2]  
[4 9]  
[5 6]]
226(3, 2)
3-D Array[[[ 1 2]
[ 3 4]
[10 11]]
[[ 5 6]
[ 8 9]
[12 13]]]
3312(2, 3, 2)

The following few program examples show how to find various attributes of 1-D and 2-D ndarray.

print("Program Name: ndim_shape_size_dtype.py \n")
import numpy as np
#Array 1D
array1d = np.array([1, 2, 6, 8])
print("array1d is \n", array1d)
print("ndim of array1d is : ", array1d.ndim)
print("shape of array1d is : ", array1d.shape)
print("size of array1d is : ",array1d.size)
print("dtype of array1d is :",array1d.dtype)
print()
#
# Array 2D
array2d = np.array([[1, 2], [4, 9], [5, 6]])
print("array2d is : \n", array2d)
print()
print("ndim of array2d is : ", array2d.ndim)
print("shape of array2d is : ", array2d.shape)
print("size of array2d is : ",array2d.size)
print("dtype of array2d is :",array2d.dtype)
print()

The following is the program’s output of 1-D and 2-D ndarray attributes:

Array attributes of 1D and 2D arrays.py
Program Name: ndim_shape_size_dtype.py

array1d is
[1 2 6 8]
ndim of array1d is : 1
shape of array1d is : (4,)
size of array1d is : 4
dtype of array1d is : int32

array2d is :
[[1 2]
[4 9]
[5 6]]

ndim of array2d is : 2
shape of array2d is : (3, 2)
size of array2d is : 6
dtype of array2d is : int32

# ndarray attributes of Array Float type and Array Complex type
import numpy as np
array2df= np.array([[1.1, 2], [4, 9], [5, 6]])
print("2-D array2df is: \n ", array2df)
print()
print("dtype of 2-D array2df is:\n",array2df.dtype)
print()
print("Specify dtype while creating an floating-point array. \n")
#
array2df1 = np.array([[1, 2], [4, 9], [5, 6]],dtype = float)
print("2-D array2df1 is:\n ", array2df1)
print()
print("dtype of array2df1 is: \n",array2df1.dtype)

print("----- End of 2-D float array section ------ \n")
# Array Complex
array2dcomp= np.array([[1+1j, 2], [4, 9], [5, 6]])
print("2-D Complex array array2dcomp is: \n ", array2dcomp)
print()
print("dtype of array2dcomp is: \n",array2dcomp.dtype)
print()
print("Create another 2D Complex array by specifying dtype \n")
array2dc= np.array([[1, 2], [4, 9], [5, 6]],dtype = complex)
print("2-D complex array array2dc is : \n ", array2dc)
print()
print("dtype of 2-D complex array array2dc is :",array2dc.dtype)

The following is the programs’s output:

Array Float type and complex type.py
2-D array2df is:
[[1.1 2. ]
[4. 9. ]
[5. 6. ]]

dtype of 2-D array2df is:
float64

Specify dtype while creating an floating-point array.

2-D array2df1 is:
[[1. 2.]
[4. 9.]
[5. 6.]]

dtype of array2df1 is:
float64
—– End of 2-D float array section ——

2-D Complex array array2dcomp is:
[[1.+1.j 2.+0.j]
[4.+0.j 9.+0.j]
[5.+0.j 6.+0.j]]

dtype of array2dcomp is:
complex128

Create another 2D Complex array by specifying dtype

2-D complex array array2dc is :
[[1.+0.j 2.+0.j]
[4.+0.j 9.+0.j]
[5.+0.j 6.+0.j]]

dtype of 2-D complex array array2dc is : complex128

# Array attributes of 3D array
import numpy as np
array3d = np.array([[[1, 2], [3, 4], [10, 11]], [[5, 6], [8, 9], [12, 13]]])
print("array3d is : \n ", array3d)
print()
print("ndim of array3d is : ", array3d.ndim)
print("shape of array3d is : ", array3d.shape)
print("size of array3d is : ",array3d.size)
print("dtype of array3d is :",array3d.dtype)
print()

The following is the output of the 3-D array attributes program:

array_ndim\Array attributes of 3D array.py
array3d is :
[[[ 1 2]
[ 3 4]
[10 11]]

[[ 5 6]
[ 8 9]
[12 13]]]

ndim of array3d is : 3
shape of array3d is : (2, 3, 2)
size of array3d is : 12
dtype of array3d is : int32

The following program prints the ndarray attributes for floting-point and complex numbers data types.

# ndarray attributes of Array Float type and Array Complex type
import numpy as np
array2df= np.array([[1.1, 2], [4, 9], [5, 6]])
print("2-D array2df is: \n ", array2df)
print()
print("dtype of 2-D array2df is:\n",array2df.dtype)
print()
print("Specify dtype while creating an floating-point array. \n")
#
array2df1 = np.array([[1, 2], [4, 9], [5, 6]],dtype = float)
print("2-D array2df1 is:\n ", array2df1)
print()
print("dtype of array2df1 is: \n",array2df1.dtype)

print("----- End of 2-D float array section ------ \n")
# Array Complex
array2dcomp= np.array([[1+1j, 2], [4, 9], [5, 6]])
print("2-D Complex array array2dcomp is: \n ", array2dcomp)
print()
print("dtype of array2dcomp is: \n",array2dcomp.dtype)
print()
print("Create another 2D Complex array by specifying dtype \n")
array2dc= np.array([[1, 2], [4, 9], [5, 6]],dtype = complex)
print("2-D complex array array2dc is : \n ", array2dc)
print()
print("dtype of 2-D complex array array2dc is :",array2dc.dtype)

The following is the floating-point and complex number program’s output:

Array Float type and complex type.py
2-D array2df is:
[[1.1 2. ]
[4. 9. ]
[5. 6. ]]

dtype of 2-D array2df is:
float64

Specify dtype while creating an floating-point array.

2-D array2df1 is:
[[1. 2.]
[4. 9.]
[5. 6.]]

dtype of array2df1 is:
float64
—– End of 2-D float array section ——

2-D Complex array array2dcomp is:
[[1.+1.j 2.+0.j]
[4.+0.j 9.+0.j]
[5.+0.j 6.+0.j]]

dtype of array2dcomp is:
complex128

Create another 2D Complex array by specifying dtype

2-D complex array array2dc is :
[[1.+0.j 2.+0.j]
[4.+0.j 9.+0.j]
[5.+0.j 6.+0.j]]

dtype of 2-D complex array array2dc is : complex128

Array Creation Functions

NumPy offers several functions to create arrays with initial placeholder content.

Some of these functions are listed in the table below:

Table: Array Creation Functions

FUNCTIONDESCRIPTION
Function zeros The function zeros creates an array full of zeros.
Function ones The function ones creates an array full of ones.
Function empty The function empty creates an array whose initial content is random and depends on the state of the memory.
Numpy.arrangeThis function creates a sequences of evenly spaced values within a specified range.
Numpy.linspaceThis function creates arrays with a specified number of elements in the array, and spaced equally between the specified beginning and end values
Numpy.identityThe NumPy identity array is a square matrix with ones on the main diagonal and zeros elsewhere.

These functions are further described below:

Numpy.arange Function

The numpy.arange() function creates an array of evenly spaced values within a specified range.

Numpy.arange() can handle both integer and floating-point numbers. It allows negative steps to generate descending sequences.

Uses: This function is used for generating sequences for loops and mathematical calculations.

For details of the arange() function, click on the link below:

https://numpy.org/doc/stable/reference/generated/numpy.arange.html

numpy.arange() function Usage Examples

Example DescriptionCode ExampleResult
Basic integer sequencenp.arange(5)[0, 1, 2, 3, 4]
Custom range with start and stopnp.arange(2, 10)[2, 3, 4, 5, 6, 7, 8, 9]
Stepped sequencenp.arange(0, 20, 3)[0, 3, 6, 9, 12, 15, 18]
Floating-point sequencenp.arange(1.0, 5.0, 0.5)[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
Descending sequencenp.arange(10, 2, -2)[10, 8, 6, 4]

Return value:

numpy.arange() returns a NumPy array of evenly spaced values within a specified range.

Numpy.arange() syntax:

Array1 = np.array([start], stop [, step], dtype = none)

Parameters:

ParameterDescription
StartStart is the starting value of the array (Optional). If not specified, start will default to zero.
StopStop is the end of the array.  The array creation will stop just before the specified stop value.
StepStep (Optional): Spacing between values. If not specified, Step defaults to 1.

The program below uses the reshape() function, which is discussed in a later section.

print("Program Name: numpy_arange.py \n")
import numpy as np
print("Examples of arange() function usage. \n")
# arange() Function programs
# Create a 1-D array of 5 elements evenly spaced by 3
array1d = np.arange(0, 15, 3)
print("1-D array of 5 elements between 0 and 15 spaced by 3 is : \n" , array1d)
print()
# Create a 1-D array between 2 and 20 evenly spaced by 6
array1d1 = np.arange(2, 20, 6)
print("1-D array starting from 2 to 20 spaced by 6 is : \n" , array1d1)
print()
# Create a 2D array of 20 elements using arange() function
array2d = np.arange(20).reshape(4, 5)
print("2-D 4X5 array of 20 elements spaced evenly by 1 is : \n", array2d)
print()
# Create a 2D 3X5 array using arange() function
array2d1 = np.arange(0, 45, 3).reshape(3, 5)
print("2-D 3X5 array of 15 elements spaced evenly by 3 is : \n", array2d1)

The following is the arange() program’s output:

Program Name: numpy_arange.py

Example of arange() function usage.

1-D array of 5 elements between 0 and 15 spaced by 3 is :
[ 0 3 6 9 12]

1-D array starting from 2 to 20 spaced by 6 is :
[ 2 8 14]

2-D 4X5 array of 20 elements spaced evenly by 1 is :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]

2-D 3X5 array of 15 elements spaced evenly by 3 is :
[[ 0 3 6 9 12]
[15 18 21 24 27]
[30 33 36 39 42]]

Numpy.linspace Function

Numpy.linspace() function creates arrays with a specified number of elements in the array, and spaced equally between the specified beginning and end values. NumPy will calculate the spacing between the numbers automatically.

The linspace() function provides precise control over numerical ranges.

For more details refer to the link below.

https://numpy.org/doc/stable/reference/generated/numpy.linspace.html

Return value:

linspace() function returns num evenly spaced numbers over a specified interval calculated over the interval [startstop].

Syntax of linspace():

numpy.linspace(startstopnum=50endpoint=Trueretstep=Falsedtype=Noneaxis=0*device=None)

Keyword Arguments:

ParameterDescription
start:The starting value of the sequence. (optional). Default: start = 0
stop:stop: The end value of the sequence
num:num: Number of samples to generate. Default is 50. Must be non-negative (optional).
retsteIf True, stop is the last sample.   By default, retstep = False
endpointIf True, stop is included as the last value. If False, stop is excluded. By default, endpoint=True.
dtypeType of output array (optional)
axisIf start and stop are arrays, axis specifies on what axis will the values be added. If axis = 0, value is added to front, if axis = -1 value is added at the end.
numpy.linspace() Function

Usage Example of linspace() function:

Example CodeOutput
np.linspace(0, 10, 5)[ 0. 2.5 5. 7.5 10.]
np.linspace(0, 10, 4, endpoint=False)[0. 3.33333333 6.66666667]
np.linspace(0, 10, 5, retstep=True)(array([ 0. , 2.5, 5. , 7.5, 10. ]), 2.5)

The following program shows the functionality of the linspace() function.

print("PROGRAM NAME: numpy_linspace.py \n")
import numpy as np
print("Examples of linspace() programs \n")
# create a 1-D array of 5 evenly spaced numbers from 0 to 1
array1d = np.linspace(0, 1, 5)
print("1-D array of 5 evenly spaced elements between 0 and 1 is: \n", array1d)  
print()
#
# Create a 1-D array of 10 elements between 0 and 10
array1d1 = np.linspace(0, 10, num = 10, endpoint = False)
print("1-D array of 10 evenly-spaced elements between o and 10 is: \n", array1d1)
print()

# Create a 1-D array of 50 elements between 0 and 10.
# without parameter num, with endpoint=False, and retstep=False
arr1d = np.linspace(0, 10, endpoint = False, retstep = False)
print("1-D array of 10 evenly-spaced elements between 0 and 10 is: \n", arr1d)
print()
#
array2d = np.linspace(1, 20, num = 20).reshape(5, 4)
print("2-D array of 20 elements between 0 and 20 is: \n", array2d)

The following is the linspace() program’s output:

PROGRAM NAME: numpy_linspace.py

Examples of linspace() programs

1-D array of 5 evenly spaced elements between 0 and 1 is:
[0. 0.25 0.5 0.75 1. ]

1-D array of 10 evenly-spaced elements between o and 10 is:
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

1-D array of 10 evenly-spaced elements between 0 and 10 is:
[0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. 2.2 2.4 2.6 2.8 3. 3.2 3.4
3.6 3.8 4. 4.2 4.4 4.6 4.8 5. 5.2 5.4 5.6 5.8 6. 6.2 6.4 6.6 6.8 7.
7.2 7.4 7.6 7.8 8. 8.2 8.4 8.6 8.8 9. 9.2 9.4 9.6 9.8]

2-D array of 20 elements between 0 and 20 is:
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]
[13. 14. 15. 16.]
[17. 18. 19. 20.]]

General Array Creation Functions

The ndarray provides a few array creation functions, e.g., numpy.onesnumpy.zeros to define arrays based upon the desired shape. The ndarray creation functions can create arrays:

  • Of any dimension by specifying the number of dimensions and
  • Length along that dimension in a tuple or list.

Numpy.ones() Function

The numpy.ones() function is used to create an array filled with ones. This function is particularly useful for initializing arrays in mathematical computations or algorithms.

For details refer to the link below:

https://numpy.org/doc/stable/reference/generated/numpy.ones.html

Syntax:

numpy.ones(shapedtype=Noneorder=’C’*device=Nonelike=None)

Return value:

The function returns a new array of the given shape and type, filled with ones.

Parameters:

ParameterDescriptionExample
shape : int or sequence of intsShape of the new arrayTuple e.g. (2,3) or 2
dtype : data-type(Optional) The desired data-type for the arraye.g., numpy.int8. Default is numpy.float64.
Order : {‘C’, ‘F’}(Optional) Store multi-dimensional data in row-major (C-style) or column-major (F-style) order in memory.Default: C
Device :Optionalstr
numpy.ones() Function

The program example shows how to generate an array filled with 1’s.

# ndarray numpy.ones()
print("numpy.ones PROGRAM EXAMPLES")
import numpy as np
# Create a 1D array of size 6 filled with ones
ones1d = np.ones(6)
print("A 1D ones array of size 6 : \n", ones1d)
print()
# Create a 2D ones array of size 2x6 filled with ones
ones2d = np.ones((2,6))
print("A 2D ones array of size 2x6 : \n", ones2d)
print()
# Create a 3D ones array of size 2x5x3 filled with ones
ones3d = np.ones((2, 5, 3))
print("A 3D ones array of size 2x5x3 : \n", ones3d)
print()

The following is the program’s output:

numpy.ones PROGRAM EXAMPLES
A 1D ones array of size 6 :
[1. 1. 1. 1. 1. 1.]

A 2D ones array of size 2×6 :
[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]

A 3D ones array of size 2x5x3 :
[[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]

[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]]

numpy.zeros() Function

The numpy.zeros() function is used to create an array filled with zeros. It is used for creating placeholders before filling them with actual data.

This function is particularly useful for initializing arrays in mathematical computations or algorithms, where you may not have initial values. 

For more details, refer to the link below:

https://numpy.org/doc/stable/reference/generated/numpy.zeros.html#numpy.zeros

numpy.zeros Syntax:

numpy.zeros(shapedtype=Noneorder=’C’*device=Nonelike=None)

Return Value.

numpy.zeros() returns a new array of given shape and type, filled with zeros.

Parameters:

ParameterDescriptionExample
shape:
int or tuple of ints
Shape of the new array. An integer for a 1D array or a tuple for multi-dimensional arrayse.g., (2, 3) or 2.
dtype:
data-type
(Optional) The desired data-type for the array elementse.g., numpy.int8. Default is numpy.float64.
order :
{‘C’, ‘F’}
(Optional) Defines memory layout. Whether to store multi-dimensional data in row-major (C-style) or column-major (F-style) order in memory.default: ‘C’
Device :Optionalstr
# naarray numpy.zeros()
print("numpy.zeros PROGRAM EXAMPLES")
import numpy as np
# Create a 1D array of size 6 filled with zeros
zeros1d = np.zeros(6)
print("A 1D array of size 6 : \n", zeros1d)
print()
# Create a 2D array of size 2x6 filled with zeros
zeros2d = np.zeros((2,6))
print("A 2D array of size 2x6 : \n", zeros2d)
print()
# Create a 3D array of size 2x5x3 filled with zeros
zeros3d = np.zeros((2, 5, 3))
print("A 3D array of size 2x5x3 : \n", zeros3d)
print()

The following is the program’s output:

numpy.zeros PROGRAM EXAMPLES
A 1D array of size 6 :
[0. 0. 0. 0. 0. 0.]

A 2D array of size 2×6 :
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]

A 3D array of size 2x5x3 :
[[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]]

Numpy.identity() Function

The identity array can be created using numpy.identity() function, which takes the size of the matrix as an argument. The identity array is always square i.e., it has the same number of rows and columns. It has ones on the main diagonal (from the top left to the bottom right) and zeros elsewhere.

When multiplied by any matrix of compatible dimensions, it returns the original matrix.

Identity() function is used in linear algebra computations to represent a matrix that doesn’t change a vector when multiplied by it.

Syntax:

numpy.identity(n, dtype=None)

n = dimension of the square array.

Return value:

identity() [ndarray] returns an n x n array with its main diagonal set to one, and all other elements set to 0.

You can create an identity array in NumPy using the numpy.identity() function as in the program below.

# Numpy Identity Array
print("Program name: numpy_identity.py \n")
import numpy as np
# Create a 3x3 identity aarray
identityarray = np.identity(3)
print("3x3 identity array is : \n", identityarray)
print()

The following is identity() function program’s output.

Program name: numpy_identity.py

3×3 identity array is :
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

Verified by MonsterInsights