在Numpy中沿轴1对多维数组应用累加


要累加对所有元素应用运算符的结果,请使用Python Numpy中的**numpy.accumulate()**方法。对于多维数组,累加仅沿一个轴应用。我们将沿轴1应用。

**numpy.ufunc**具有对整个数组逐元素操作的函数。ufunc是用C语言编写的(为了速度)并与NumPy的ufunc工具链接到Python。通用函数(简称ufunc)是一个逐元素操作ndarray的函数,支持数组广播、类型转换和几个其他标准特性。也就是说,ufunc是函数的“矢量化”包装器,它接受固定数量的特定输入并产生固定数量的特定输出。

步骤

首先,导入所需的库:

import numpy as np

创建一个二维数组。numpy.eye()返回一个二维数组,对角线为1,其他位置为0:

arr = np.eye(3)

显示数组:

print("Array...
", arr)

获取数组的类型:

print("
Our Array type...
", arr.dtype)

获取数组的维度:

print("
Our Array Dimensions...
",arr.ndim)

要累加对所有元素应用运算符的结果,请使用Python Numpy中的numpy.accumulate()方法。对于多维数组,累加仅沿一个轴应用:

添加累加:沿轴1(列)累加:

print("
Add accumulate...
",np.add.accumulate(arr, 1))

乘法累加:

print("
Multiply accumulate...
",np.multiply.accumulate(arr, 1))

示例

import numpy as np
import numpy.ma as ma

# The numpy.ufunc has functions that operate element by element on whole arrays.
# ufuncs are written in C (for speed) and linked into Python with NumPy’s ufunc facility

# Create a 2d array
# The numpy.eye() returns a 2-D array with 1’s as the diagonal and 0’s elsewhere.
arr = np.eye(3)

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimensions...
",arr.ndim) # To Accumulate the result of applying the operator to all elements, use the numpy.accumulate() method in Python Numpy # For a multi-dimensional array, accumulate is applied along only one axis # Add accumulate # Accumulate along axis 1 (columns) # Add accumulate print("
Add accumulate...
",np.add.accumulate(arr, 1)) # Multiply accumulate print("
Multiply accumulate...
",np.multiply.accumulate(arr, 1))

输出

Array...
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

Our Array type...
float64

Our Array Dimensions...
2

Add accumulate...
[[1. 1. 1.]
[0. 1. 1.]
[0. 0. 1.]]

Multiply accumulate...
[[1. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

更新于:2022年2月5日

209 次查看

启动您的职业生涯

完成课程获得认证

开始
广告