Loading, please wait...

A to Z Full Forms and Acronyms

Methods of Universal function(part-2)|Python tutorial

This article covers methods of NumPy universal function i.e ufuncs.

Methods of Universal function(part-2)|Python tutorial

Before getting into this article, I would suggest you read part-1 so that you know the basics of ufunc. In this article, you will learn only the methods of the ufuncs with code examples in brief. 

There are four methods of ufuncs & these methods make sense on scalar ufuncs that takes only two arguments as input and returns one output argument. If you try to call these methods on other ufuncs ValueError will be raised. ufuncs methods are listed below.

1. ufunc.reduce():

This method reduces a’s dimension by one, by applying ufunc along one axis.

Syntax:

ufunc.reduce(a, axis=0, dtype=None, keepdims=False, out=None)

Parameters:

 a: input array

axis: It can be None or tuple of ints, optional. Default axis=0 i.e it performs reduce on the first dimension of the input array. It may be negative too, in which case it counts from the last to the first axis.

If axis=None: reduction overall axes

If a tuple of ints: reduction over multiple axes.

dtype: optional, data type 

Used to represent the intermediate results. Defaults to the output array, if provided otherwise input array.

out: output array, optional

If not provided then it returns freshly allocated array

keepdims: bool, optional   

If set to True, the axes which are reduced are left in the result as dimensions with size one, with this option, the result broadcasts correctly against the original array.

#Code to demonstrate the working of reduce() method with a one- dimensional array.

1. add.reduce()

#add.reduce() is equivalent to sum()
import numpy as np

x= np.add.reduce([1,2,3,4,5,6])

print(x)

#output: 21




2. subtract.reduce()

#subtract.reduce() is equivalent to subtract()
import numpy as np

x= np.subtract.reduce([1,2,3,4,5,6])

#it works like arr[0]-arr[1]-arr[2]-arr[3]-arr[4]-arr[5]

print(x)

#output: -19

 

3. multiply.reduce()

#multiply.reduce() is equivalent to multiply()
import numpy as np

x= np.multiply.reduce([1,2,3,4,5,6])

#it works like arr[0]*arr[1]*arr[2]*arr[3]*arr[4]*arr[5]

print(x)

#output: 720

#Code to demonstrate working of reduce() method with a multi- dimensional array.

import numpy as np
#creating numpy array using arange() and reshaping it
y= np.arange(8).reshape((2,2,2))

print(y)

#output:

#[ [[0 1] [2 3]]

#[[4 5] [6 7]] ]




arr1= np.multiply.reduce(y) #default axis=0

print(arr1)

#output:[[ 0 5]

# [12 21]]




arr2= np.multiply.reduce(y,0) #axis =0 will also reduce the same as default

print(arr2)

#output:

# [[ 0 5]

# [12 21]]




arr3= np.multiply.reduce(y,1) #along axis =1

print(arr3)

#output:

# [[ 0 3]

# [24 35]]



arr4= np.multiply.reduce(y,2) #along axis=2

print(arr4)

#output:

#[[ 0 6]

# [20 42]]





2. ufunc.accumulate():

This method accumumulate the result of applying the operator to all elements.

Syntax:

ufunc.accumulate(a, axis=0, dtype=None, out=None)

Parameters: 

a: input array

axis: It can be int, optional. Default is zero, it defines the axis along which to perform accumulation.

dtype: optional, data type 

Used to represent the intermediate results. Defaults to the output array, if provided otherwise input array.

out: output array, optional

If not provided then it returns freshly allocated array.      

Returns: ‘r’ ndarrays with accumulated values.

#Code to demonstrate working of accumulate() method with a one- dimensional array.

import numpy as np

#multiply.accumulate()

x= np.multiply.accumulate([1,2,3,4,5,6])

print(x)

#output:[ 1 2 6 24 120 720]
import numpy as np

#add.accumulate()

x= np.add.accumulate([1,2,3,4,5,6])

print(x)

#output:[ 1 3 6 10 15 21]

#Code to demonstrate the working of accumulate() method with a multidimensional array.

          

import numpy as np 

y= np.arange(8).reshape((2,2,2))

print(y)

#output:

#[ [[0 1] [2 3]]

#[[4 5] [6 7]] ]




arr1= np.multiply.accumulate(y) #default axis=0

print(arr1)

#output:[[[ 0 1]

  [ 2 3]]




 [[ 0 5]

  [12 21]]]




arr2= np.multiply.accumulate(y,0) #axis =0 will also reduce the same as default

print(arr2)

#output:[[[ 0 1]

  [ 2 3]]




 [[ 0 5]

  [12 21]]]




arr3= np.multiply.accumulate(y,1) #along axis =1

print(arr3)

#output:[[[ 0 1]

  [ 0 3]]




 [[ 4 5]

  [24 35]]]




arr4= np.multiply.accumulate(y,2) #along axis=2

print(arr4)

#output:

[[[ 0 0]

  [ 2 6]]




 [[ 4 20]

  [ 6 42]]]





3. ufunc.reduceat():

This method performs reduce at specified slices over a single axis.

Syntax:  

ufunc.reduceate(a, indices, axis=0,dtype=None,out=None)

Parameters: 

a: input array

axis: It can be int, optional. Default is zero, it defines the axis along which to perform reduced.

dtype: optional, data type 

Used to represent the intermediate results. Defaults to the output array, if provided otherwise input array.

out: output array, optional

If not provided then it returns freshly allocated array.      

Returns: ‘r’ ndarrays with reduced values.

For Example:

import numpy as np

arr =np.arange(15)

indices=np.array([1,3,5,6])

outarry= np.add.reduceat(arr,indices)

print(outarry)

#output:[ 3 7 5 90]

Explanation: reduceat() is applying to reduce() method repeatedly over the array-like shown below:

print("step1 : ", np.add.reduce(arr[1:3]))

print("step2 : ", np.add.reduce(arr[3:5]))

print("step3 : ", np.add.reduce(arr[5:6]))

print("step4 : ", np.add.reduce(arr[6:]))

#output:

step1 : 3

step2 : 7

step3 : 5

step4 : 90

# and appends the result of each step to a list and print the final result.

4.ufunc.outer(): 

This method applies the ufunc operator to all pairs (a,b) with 'a' in Array1 and b in Array2.

Syntax:

ufunc.outer(a, b ,**kwargs)

Parameters:

a: first input array or array_like.

b: second input array or array_like.

kwargs: any argument to pass onto ufunc, i.e dtype or out.

Returns: ‘r’ ndarray

#code to demonstrate the working of ufunc.outer() with the 1-D array.

import numpy as np

arr = np.add.outer([1,2,3,4,5],[6,7,8,9,10])

print(arr)

#output:[[ 7 8 9 10 11]

# [ 8 9 10 11 12]

# [ 9 10 11 12 13]

# [10 11 12 13 14]

# [11 12 13 14 15]]

#code to demonstrate the working of ufunc.outer() with the multi-dimensional array.

import numpy as np

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

print(arr1.shape)

#Output: (2,5)

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

print(arr2.shape)

#Output: (1,5)

arr3 =np.multiply.outer(arr1,arr2)

print(arr3.shape)

#Output: (2, 5, 1, 5)




print(arr3)

#output:[[[[ 1 2 3 4 5]]

  [[ 2 4 6 8 10]]

  [[ 3 6 9 12 15]]

  [[ 4 8 12 16 20]]

  [[ 5 10 15 20 25]]]

 [[[ 6 12 18 24 30]]

  [[ 7 14 21 28 35]]

  [[ 8 16 24 32 40]]

  [[ 9 18 27 36 45]]

  [[10 20 30 40 50]]]]





5. ufunc.at():

This method performs unbuffered in place operation on operand ‘a’ for elements specified by indices.

Syntax: 

ufunc.at(a, indices, b=None)

Parameters:

a: array to operate on.

indices: array-like or a tuple

b: second operand for ufuncs requiring two operands

For Example:

#set items at 1 and 3 to their negative values:

 
import numpy as np

arr=np.array([10,20,30,40,50])

np.negative.at(arr, [1,3])

print(arr)

#output:[ 10 -20 30 -40 50]





#multiply items at 1 and 3 by second operand 10:

import numpy as np

arr=np.array([10,20,30,40,50])

np.multiply.at(arr, [1,3], 10)

print(arr)

#output:[ 10 200 30 400 50]




            

Thanks for reading this article. I just hope you like the content, please don’t forget to comment and share the content with your friends. Stay tuned with us for more articles like this.

With regards,

Keep learning

A to Z Full Forms and Acronyms

Related Article