numpy.apply_along_axis () in Python



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 

What are * args and ** kwargs?
Both of them allow variable # to be passed. function arguments. 
* args: Allow sending a variable-length argument list without a keyword to the function.

# Python program illustrating
# using * arguments

 

args = [ 3 , 8 ]

a = list ( range ( * args))

print ( "use of args : " , a)

Exit:

 use of args: [3, 4, 5, 6, 7] 

** kwargs: allows you to pass a keyword of variable length argument into a function. It is used when we want to process a named argument in a function.

# Python program illustrating
# using ** kwargs

 

def test_args_kwargs (in1, in2, in3):

print ( "in1:" , in1)

print ( " in2: " , in2)

  print ( " in3: " , in3)

  

 

kwargs = { "in3" : 1 , "in2" : "No." , "in1" : "geeks" }

test_args_kwargs ( * * kwargs )

Output:

 in1: geeks in2: No. in3: 1 

Code 1: Python code explaining the use of numpy.apply_along_axis ().

# Python program illustrating
# apply_along_axis () in NumPy

 

import numpy as geek 

  
# 1D_func - & quot; geek_fun & quot;

def geek_fun (a):

# Returns the sum of the elements in the initial and last index

# inout array

return (a [ 0 ] + a [ - 1 ])

 

arr = geek.array ([[ 1 , 2 , 3 ], 

[ 4 , 5 , 6 ], 

[ 7 , 8 , 9 ]])

 
"" "

- & gt; [1,2,3] & lt; - 1 + 7

[4,5, 6] 2 + 8

- & gt; [7,8,9] & lt; - 3 + 9

"" " 

print ( "axis = 0:" , geek .apply_along_axis (geek_fun, 0 , arr))

print ( " " )

 
& # 39; & # 39; & # 39; | |

[1,2,3] 1 + 3

[4,5,6] 4 + 6

[7,8,9] 7 + 9

  ^ ^

"" " 

print ( " axis = 1: " , geek.apply_along_axis (geek_fun, 1 , arr))

Output:

 axis = 0: [8 10 12] axis = 1: [ 4 10 16] 

Code 2: Sort using apply_along_axis () in NumPy Python

# Program Python, silt lustrating
# apply_along_axis () in NumPy

 

import numpy as geek 

 

geek_array = geek.array ([[ 8 , 1 , 7 ],

[ 4 , 3 , 9 ],

[ 5 , 2 , ]])

 
# using a predefined sorted function like 1D_func

print ( " Sorted as per axis 1: " , geek.apply_along_axis ( sorted , 1 , geek_array))

  

print ( " " )

 

print ( " Sorted as per axis 0: " , geek .apply_along_axis ( sorted , 0 , geek_array))

Output:

 Sorted as per axis 1: [[1 7 8] [3 4 9] [2 5 6]] Sorted as per axis 0: [[4 1 6] [5 2 7] [8 3 9]] 

Notes:
These NumPy-Python programs will not run by onlineID, so run them on your systems to learn them
,
This article is provided by Mohit Gupta_OMG