5 Must know NumPy Functions !
Tags: Numpy Broadcasting, Numpy Array, Numpy Functions, Numpy

Let’s begin by importing NumPy and listing out the functions covered in this article.

import numpy as np ### List of functions explained

-function1 = np.array_split()

-function2 = np.where()

-function3 = np.sort()

-function4 = np.lcm()

-function5 = np.unique()

Function 1 — np.array_split

This function is used to split an array into multiple sub-arrays equally.

x = np.arange(8)

np.array_split(x,2,axis=0) [array([0, 1, 2, 3]), array([4, 5, 6, 7])]

The above example shows how to split an array by passing arguments — array , number of splits and axis(optional)

y = np.array([[1,2,3],[4,5,6],[7,8,9]])

np.array_split(y,3) [array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]])]

The above example splits the array in 3 sub-arrays.

# Example- breaking (to illustrate when it breaks)

y = np.array([[1,2,3],[4,5,6],[7,8,9]])

np.array_split(y,2,axis=2) ---------------------------------------------------------------------------



IndexError Traceback (most recent call last)



/tmp/ipykernel_286/3211635656.py in <module>

1 y = np.array([[1,2,3],[4,5,6],[7,8,9]])

----> 2 np.array_split(y,2,axis=2)





<__array_function__ internals> in array_split(*args, **kwargs)





/opt/conda/lib/python3.9/site-packages/numpy/lib/shape_base.py in array_split(ary, indices_or_sections, axis)

765 """

766 try:

--> 767 Ntotal = ary.shape[axis]

768 except AttributeError:

769 Ntotal = len(ary)





IndexError: tuple index out of range

The above example errors with an Index error essentially as we have provided axis = 2 ,but the array is 2-D so the axes can either be 0 or 1. To avoid this identify the shape of the array.

Function 2 — np.where

numpy.where(condition[,x,y])

This function returns values x ,y based on condition provided.

a = np.array([1,2,3,4]) np.where(a%2==0,'even','odd') array(['odd', 'even', 'odd', 'even'], dtype='<U4')

The above example demonstrate use of where function , it return ‘even’ when the condition is True and ‘odd’ when the condition fails.

b = np.array([[1,2,3],[4,5,6]])



np.where([[True,False,True]],b,False) array([[1, 0, 3],

[4, 0, 6]])

This example demonstrates use of Where function on multidimensional array , both the return values are broadcasted.

# Example- breaking (to illustrate when it breaks)

c = np.array([[1,2,3],[4,5,6]])



np.where([[True,False]],c,False) ---------------------------------------------------------------------------



ValueError Traceback (most recent call last)



/tmp/ipykernel_286/2683844110.py in <module>

2 c

3 c.shape

----> 4 np.where([[True,False]],c,False)





<__array_function__ internals> in where(*args, **kwargs)





ValueError: operands could not be broadcast together with shapes (1,2) (2,3) ()

As we see a Value error occurs when array could not be broadcasted , to avoid this use compatible shape.

Function 3 — np.sort

This function is used to get a sorted array.

a = np.array([[2,1],[7,4]]) np.sort(a,axis=None) #sort the flattened array array([1, 2, 4, 7])

The sort function returns an sorted array , in the above example the array is flattened as axis = None ,you can try changing the axis and see the results .

b = [('Sam',20),('Ram',30),('Sham',70)]

fields = [('Name','S10'),('age',int)]

c=np.array(b,dtype=fields) #created a structured array

np.sort(c,order='age') #sort by age array([(b'Sam', 20), (b'Ram', 30), (b'Sham', 70)],

dtype=[('Name', 'S10'), ('age', '<i8')])

The above example shows us how to use order in sort function , the array is sorted first with age and then Name if they are equal.

# Example- breaking (to illustrate when it breaks)

c = np.array([[[2,3],[3,4],[4,5]],

[[2,3],[7,8],[8,9]]])



c.shape # 2,3,2 array size



np.sort(c,kind='heap',axis = 3) ---------------------------------------------------------------------------



AxisError Traceback (most recent call last)



/tmp/ipykernel_286/3643130667.py in <module>

5 c.shape # 2,3,2 array size

6

----> 7 np.sort(c,kind='heap',axis = 3)





<__array_function__ internals> in sort(*args, **kwargs)





/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in sort(a, axis, kind, order)

996 else:

997 a = asanyarray(a).copy(order="K")

--> 998 a.sort(axis=axis, kind=kind, order=order)

999 return a

1000





AxisError: axis 3 is out of bounds for array of dimension 3

As seen above we will get a Axis error as the array we provided is 3-D and we wanted to sort it along the 4th axis which is not available hence it errors to avoid this verify the shape of your array firsthand.

Function 4 — np.lcm

This function is used to easily calculate lcm of arrays. Lcm is the least common multiple of the absolute values of the inputs.

a = [1,2,3]

b = [4,5,6]

np.lcm(a,b) array([ 4, 10, 6])

In the above example the function accepts input of the common shape and get us the lcm respectively.

x = [1,2]

y = [[3,]] # Broadcasting is done for this array.

np.lcm(x,y) array([[3, 6]])

The above example perfectly shows how broadcasting is done in NumPy.

# Example- breaking (to illustrate when it breaks)

x = [1,2]

y = [3,4,5,6]

np.lcm(x,y) ---------------------------------------------------------------------------



ValueError Traceback (most recent call last)



/tmp/ipykernel_286/2014791491.py in <module>

1 x = [1,2]

2 y = [3,4,5,6]

----> 3 np.lcm(x,y)





ValueError: operands could not be broadcast together with shapes (2,) (4,)

In the above example x & y could not be broadcasted together hence the fuction returns Value Error.

Function 5 — np.unique

This functions returns unique elements of the input array.

a = np.array([7,2.0,2,2,'K'])

np.unique(a,return_index = True ,return_inverse = True,return_counts = True ) (array(['2', '2.0', '7', 'K'], dtype='<U32'),

array([2, 1, 0, 4]),

array([2, 1, 0, 0, 3]),

array([2, 1, 1, 1])

The function returns the unique sorted array as seen above , it also has 3 optional parameters to get the indices of the input and newly constructed unique array with the counts of the elements in the unique array .

a = np.array([[9, 1, 0], [9, 1, 0], [2, 3, 4]])

np.unique(a, axis=1) array([[0, 1, 9],

[0, 1, 9],

[4, 3, 2]])

We can also mention the axis parameter in the function ,as seen in above example .

# Example- breaking (to illustrate when it breaks)

a = np.array([[8,k],['k',4]])

np.unique(a)

-------------------------------------------------------------------- NameError Traceback (most recent call last)

<ipython-input-25-045243ee2e73> in <module>

1 import numpy as np

2

----> 3 a = np.array([[8,k],['k',4]])

4 np.unique(a)



NameError: name 'k' is not define

In the above example we got an Name error as k was undeclared and needs to be defined first in order to avoid the error.

This function hence can help get unique elements from the data which has different datatypes within it.

Conclusion

We have seen some useful functions here ! Hope this helps to get you started and explore many other NumPy functions .

Reference Links