當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python numpy.apply_along_axis()用法及代碼示例


numpy.apply_along_axis(1d_func,axis,array,* args,** kwargs):幫助我們將必需的函數應用於給定數組的一維切片。
1d_func(ar,* args):適用於一維數組,其中ar是沿軸的arr的一維切片。

參數:

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  

* args和** kwargs實際上是什麽?
這兩個都允許您傳遞變量號。該函數的參數。
*參數:允許向函數發送非關鍵字可變長度參數列表。


# Python Program illustrating  
# use of *args 
  
args = [3, 8] 
a = list(range(*args)) 
print("use of args  : \n   ", a)

輸出:

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

** kwargs:允許您將關鍵字的可變長度參數傳遞給函數。當我們要處理函數中的命名參數時使用它。

# Python Program illustrating  
# use of **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)

輸出:

in1: geeks
in2: No.
in3: 1

代碼1:解釋numpy.apply_along_axis()用法的Python代碼。

# Python Program illustarting 
# apply_along_axis() in NumPy 
  
import numpy as geek  
  
# 1D_func is "geek_fun" 
def geek_fun(a): 
    # Returning the sum of elements at start index and at last index 
    # inout array 
     return (a[0] + a[-1]) 
   
arr = geek.array([[1,2,3],  
                [4,5,6],  
                [7,8,9]]) 
      
''' 
              -> [1,2,3] <-   1 + 7 
                 [4,5,6]      2 + 8 
              -> [7,8,9] <-   3 + 9 
''' 
print("axis=0 : ", geek.apply_along_axis(geek_fun, 0, arr)) 
print("\n") 
  
'''             |   | 
               [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))

輸出:

axis=0 :  [ 8 10 12]


axis=1 :  [ 4 10 16]

代碼2:在NumPy Python中使用apply_along_axis()進行排序

# Python Program illustarting 
# apply_along_axis() in NumPy 
  
import numpy as geek  
  
geek_array = geek.array([[8,1,7], 
                         [4,3,9], 
                         [5,2,6]]) 
  
# using pre-defined sorted function as 1D_func 
print("Sorted as per axis 1 : \n", geek.apply_along_axis(sorted, 1, geek_array)) 
  
print("\n") 
  
print("Sorted as per axis 0 : \n", geek.apply_along_axis(sorted, 0, geek_array))

輸出:

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]]


相關用法


注:本文由純淨天空篩選整理自 numpy.apply_along_axis() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。