Python numpy.apply_over_axes()

Python numpy.apply_over_axes()

Python numpy.apply_over_axes()在一个数组的多个轴上重复应用一个函数。

语法 :

numpy.apply_over_axes(func, array, axes)

参数 :

1d_func :在一维数组上执行的必要函数。它只能应用于输入数组的一维切片,而且是沿着一个特定的轴。
axis :所需的轴,我们希望输入数组沿着这个轴被切开。
array :要工作的输入数组
*args : 1D_function的附加参数
**kwargs : 1D_function的附加参数

返回 :

输出数组。输出数组的形状可以是不同的,这取决于func 是否改变了它的输出相对于输入的形状。

代码 1 :

# Python Program illustrating
# apply_over_axis() in NumPy
 
import numpy as geek
 
# Using a 3D array
geek_array = geek.arange(16).reshape(2, 2, 4)
print("geek array  :\n", geek_array)
 
# Applying pre-defined sum function over the axis of 3D array
print("\nfunc sum : \n ", geek.apply_over_axes(geek.sum, geek_array, [1, 1, 0]))
 
# Applying pre-defined min function over the axis of 3D array
print("\nfunc min : \n ", geek.apply_over_axes(geek.min, geek_array, [1, 1, 0]))

输出 :

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

代码 2 :

# Python Program illustrating
# apply_over_axis() in NumPy
 
import numpy as geek
 
# Using a 2D array
geek_array = geek.arange(16).reshape(4, 4)
print("geek array  :\n", geek_array)
 
"""
    ->[[ 0  1  2  3]    min : 0     max : 3    sum =  0 + 1 + 2 + 3
    -> [ 4  5  6  7]    min : 4     max : 7    sum =  4 + 5 + 6 + 7
    -> [ 8  9 10 11]    min : 8     max : 11   sum =  8 + 9 + 10 + 11
    -> [12 13 14 15]]   min : 12    max : 15   sum =  12 + 13 + 14 + 15
 
"""
 
# Applying pre-defined min function over the axis of 2D array
print("\nApplying func max : \n ", geek.apply_over_axes(geek.max, geek_array, [1, -1]))
 
# Applying pre-defined min function over the axis of 2D array
print("\nApplying func min : \n ", geek.apply_over_axes(geek.min, geek_array, [1, -1]))
 
# Applying pre-defined sum function over the axis of 2D array
print("\nApplying func sum : \n ", geek.apply_over_axes(geek.sum, geek_array, [1, -1]))

输出 :

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

代码3:在不使用numpy.apply_over_axis()的情况下等效于代码2

# Python Program illustrating
# equivalent to apply_over_axis()
 
import numpy as geek
 
# Using a 3D array
geek_array = geek.arange(16).reshape(2, 2, 4)
print("geek array  :\n", geek_array)
 
# returning sum of all elements as per the axis
print("func : \n", geek.sum(geek_array, axis=(1, 0, 2), keepdims = True))

输出 :

geek array  :
 [[[ 0  1  2  3]
  [ 4  5  6  7]]

 [[ 8  9 10 11]
  [12 13 14 15]]]
func : 
 [[[120]]]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程