在 Numpy 中沿軸 0 對多維陣列應用累加


要累加對所有元素應用運算子的結果,請在 Python Numpy 中使用 **numpy.accumulate()** 方法。對於多維陣列,累加僅沿一個軸應用。我們將沿軸 0 應用。

**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() 方法。對於多維陣列,累加僅沿一個軸應用 -

新增累加:沿軸 0(行)累加 -

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

乘法累加 -

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

示例

import numpy as np

# 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 masked array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Masked 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 0 (rows) # Add accumulate print("
Add accumulate...
",np.add.accumulate(arr, 0)) # Multiply accumulate print("
Multiply accumulate...
",np.multiply.accumulate(arr, 0))

輸出

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

Our Array type...
float64

Our Array Dimensions...
2

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

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

更新於: 2022年2月7日

146 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.