numpy.apply_over_axes() in Python
Last Updated :
07 Mar, 2024
The numpy.apply_over_axes()applies a function repeatedly over multiple axes in an array.
Syntax :
numpy.apply_over_axes(func, array, axes)
Parameters :
1d_func : the required function to perform over 1D array. It can only be applied in
1D slices of input array and that too along a particular axis.
axis : required axis along which we want input array to be sliced
array : Input array to work on
*args : Additional arguments to 1D_function
**kwargs : Additional arguments to 1D_function
Return :
The output array. Shape of the output array can be different depending on whether func
changes the shape of its output with respect to its input.
Code 1 :
Python
import numpy as geek
geek_array = geek.arange( 16 ).reshape( 2 , 2 , 4 )
print ( "geek array :\n" , geek_array)
print ( "\nfunc sum : \n " , geek.apply_over_axes(geek. sum , geek_array, [ 1 , 1 , 0 ]))
print ( "\nfunc min : \n " , geek.apply_over_axes(geek. min , geek_array, [ 1 , 1 , 0 ]))
|
Output :
geek array :
[[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]]
func sum :
[[[24 28 32 36]]]
func min :
[[[0 1 2 3]]]
Code 2 :
Python
import numpy as geek
geek_array = geek.arange( 16 ).reshape( 4 , 4 )
print ( "geek array :\n" , geek_array)
print ( "\nApplying func max : \n " , geek.apply_over_axes(geek. max , geek_array, [ 1 , - 1 ]))
print ( "\nApplying func min : \n " , geek.apply_over_axes(geek. min , geek_array, [ 1 , - 1 ]))
print ( "\nApplying func sum : \n " , geek.apply_over_axes(geek. sum , geek_array, [ 1 , - 1 ]))
|
Output :
geek array :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
Applying func max :
[[ 3]
[ 7]
[11]
[15]]
Applying func min :
[[ 0]
[ 4]
[ 8]
[12]]
Applying func sum :
[[ 6]
[22]
[38]
[54]]
Code 3 : Equivalent to Code 2 without using numpy.apply_over_axis()
Python
import numpy as geek
geek_array = geek.arange( 16 ).reshape( 2 , 2 , 4 )
print ( "geek array :\n" , geek_array)
print ( "func : \n" , geek. sum (geek_array, axis = ( 1 , 0 , 2 ), keepdims = True ))
|
Output :
geek array :
[[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]]
func :
[[[120]]]
Note :
These codes won’t run on online IDE’s. Please run them on your systems to explore the working.
Share your thoughts in the comments
Please Login to comment...