NumPy ndarray – NumPy N-Dimensional Array

Free NumPy course with real-time projects Start Now!!

NumPy contains the ndarray object. It is one of the most significant features of the NumPy library for performing logical and mathematical operations. It provides an abundance of functions and methods for performing operations on the array elements. NumPy arrays are grids that contain homogenous values.

NumPy N-dimensional Array (NumPy ndarray)

Arrays in NumPy are a group of elements, mostly homogenous numbers of the same type and size. Element indexing is in the form of tuples of positive integers depending on the number of dimensions.

The values of the tuple determine the shape of the array. An array class in NumPy is ndarray. We can initialize the array elements in a range of ways.

The data type of the individual array is given by a separate data-type object (dtype). Accessing and manipulation of array elements is by indexing and slicing the array. For this purpose, we use the methods and functions of the ndarray.

Different ndarrays can also share the content. The changes then reflect in the corresponding array. An ndarray can be a “view” to another ndarray, and the data it refers to is held by the “base” array.

A basic array along with its data type is given as:

X = np.array([[0,1,2],[3,4,5]], dtype='int16')
print(X)

Output

[[0 1 2]
[3 4 5]]

Internal Memory Layout of ndarray in NumPy

An instance of the ndarray class is given a continuous segment in the memory. The memory allocation along with the indexing scheme then maps N-integers to an element of the array block. The range of index variation is given by the shape of the array and vice-versa.

The data-type object is used to define how many bytes each item will take. It also defines how the bytes will be inferred. For example, each int16 item has a size of 16 bits, I .e.16/8= 2bytes.

There are two key concepts determining the memory: dimensions and strides. Strides describe the number of bytes of each step in all the dimensions of the array when traversing through it. We can calculate the strides of an array using:
array.strides()

We can use the concept of strides to increase the execution speed.

NumPy Array attributes

The array attributes give information related to the array. Accessing array through its attributes helps to give an insight into its properties. Changes in attributes can be made of the elements, without new creations.

1. ndarray.flags- It provides information about memory layout
2. ndarray.shape- Provides array dimensions
3. ndarray.strides- Determines step size while traversing the arrays
4. ndarray.ndim- Number of array dimensions
5. ndarray.data- Points the starting position of array
6. ndarray.size- Number of array elements
7. ndarray.itemsize- Size of individual array elements in bytes
8. ndarray.base- Provides the base object, if it is a view
9. ndarray.nbytes- Provides the total bytes consumed by the array
10. ndarray.T- It gives the array transpose
11. ndarray.real- Separates the real part
12. ndarray.imag- Separates the imaginary

NumPy Indexing and Slicing

These are two very important concepts. It is useful when we want to work with sub-arrays.

Indexing starts with zero as the first index. We can retrieve element values by its index value. For 2 or more dimensional arrays, we have to specify 2 or more indices. Indexing can be of two types

1. Integer array indexing in NumPy

We pass lists for indexing in all the dimensions. Then one to one mapping occurs for the creation of a new array.

2. Boolean array indexing in NumPy

In this type of indexing, we carry out a condition check. If the boolean condition satisfies we create an array of those elements.

import numpy as np
arr=([1,2,5,6,7])
arr[3]

Output

6

Slicing is similar to indexing, but it retrieves a string of values. The range is defined by the starting and ending indices. It is similar to lists in Python. The arrays can also be sliced. The arrays can be single or multidimensional. We can specify slices for all the dimensions.

import numpy as np
arr=([1,2,5,6,7])
arr[2:5]

Output

[5, 6, 7]

Basic Operations in NumPy

Basic Operations of NumPy

1. NumPy Arithmetic Operations

We can perform arithmetic operations on the array to do an element-wise operation to create a new array. We use +=, -=, *= operators, to manipulate the existing array.

import numpy as np
 
a = np.array([1, 2, 3, 4])
 
# add 5 to every element
print ( a+5)
 
# subtract 2 from each element
print ( a-2)
 
# multiply each element by 5 
print (a*10)
 
# divide each element by 2
print ( a/2)

Output

[6 7 8 9]
[-1 0 1 2]
[10 20 30 40]
[0.5 1. 1.5 2. ]

2. NumPy Unary Operators

There are many unary operators available to perform sum, min, max, etc. We can perform these functions row or column-wise.

arr = np.array([[1,5, 12],
                [2,32, 20],
                [3, 40, 13]])
 
 
print(arr.max(axis = 1))
 
print (arr.min(axis = 0))
 
print ( arr.sum())

Output

[12 32 40]
[ 1 5 12]
128

3. NumPy Binary Operators

We can use all the arithmetic operators on the arrays and generate anew array. These operators work on two arrays and return a new array.

import numpy as np
 
a = np.array([[1, 2],
            [3, 4]])
b = np.array([[4, 3],
            [2, 1]])
 
print (a + b)
print (a*b)
print (a.dot(b))

Output

[[5 5]
[5 5]][[4 6]
[6 4]]
[[ 8 5]
[20 13]]

NumPy Universal Functions

NumPy provides many mathematical functions. These are applicable elements wise on the arrays. This includes trigonometric, exponential, and root functions.

import numpy as np
 
a = np.array([0, np.pi/2, np.pi])
print ( np.sin(a))
 
 
a = np.array([0, 1, 2, 3])
print ( np.exp(a))
 
 
print ( np.sqrt(a))

Output

[0.0000000e+00 1.0000000e+00 1.2246468e-16]
[ 1. 2.71828183 7.3890561 20.08553692]
[0. 1. 1.41421356 1.73205081]

Summary

NumPy ndarray object is the most basic concept of the NumPy library. To use the advanced features of NumPy, it is necessary to have a complete understanding of the ndarray object. The functions and methods in NumPy are all based on arrays which are instances of the ndarray class.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *