Python NumPy Broadcast() 類



NumPy 的 Broadcast() 類模擬廣播機制,並返回一個封裝了將一個數組對另一個數組進行廣播的結果的物件。此類以陣列作為輸入引數。

此類允許對不同形狀的陣列進行運算,方法是虛擬地擴充套件較小的陣列以匹配較大陣列的形狀,而無需實際在記憶體中建立更大的陣列。

語法

numpy.broadcast() 類的語法如下:

numpy.broadcast(*array_like)

引數

NumPy Broadcast() 類以 *array_like 作為輸入引數,它們是要相互廣播的輸入陣列。

返回值

它返回一個 numpy.broadcast 物件,可用於迭代陣列。

示例 1

以下是使用 NumPy Broadcast() 類建立廣播陣列的示例。此處,陣列 a 和 b 被廣播到公共形狀 (3, 3) 並逐元素迭代:

import numpy as np
scalar = 5
array_1d = np.array([1, 2, 3])
broadcast_obj = np.broadcast(scalar, array_1d)
print("Broadcasted Shape:", broadcast_obj.shape)
print("Broadcasted Elements:")
for x, y in broadcast_obj:
    print(f"({x}, {y})")

輸出

Broadcasted Shape: (3,)
Broadcasted Elements:
(5, 1)
(5, 2)
(5, 3)

示例 2

下面的示例顯示了將一維陣列 [1, 2, 3] 與二維陣列 [[4], [5], [6]] 進行廣播。一維陣列將在二維陣列的第二維上進行廣播,並建立一個適合逐元素運算的形狀:

import numpy as np

array_1d = np.array([1, 2, 3])
array_2d = np.array([[4], [5], [6]])

broadcast_obj = np.broadcast(array_1d, array_2d)

print("Broadcasted Shape:", broadcast_obj.shape)
print("Broadcasted Elements:")
for x, y in broadcast_obj:
    print(f"({x}, {y})")

輸出

Broadcasted Shape: (3, 3)
Broadcasted Elements:
(1, 4)
(2, 4)
(3, 4)
(1, 5)
(2, 5)
(3, 5)
(1, 6)
(2, 6)
(3, 6)

示例 3

在此示例中,我們將 numpy.broadcast() 類與 NumPy 庫的內建廣播機制進行比較:

import numpy as np

x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])

# Broadcasting x against y
b = np.broadcast(x, y)

# Using nditer to iterate over the broadcasted object
print('Broadcast x against y:')
for r, c in np.nditer([x, y]):
    print(r, c)
print('\n')

# Shape attribute returns the shape of the broadcast object
print('The shape of the broadcast object:')
print(b.shape)
print('\n')

# Adding x and y manually using broadcast
b = np.broadcast(x, y)
c = np.empty(b.shape)

print('Add x and y manually using broadcast:')
print(c.shape)
print('\n')

# Compute the addition manually
c.flat = [u + v for (u, v) in np.nditer([x, y])]
print('After applying the flat function:')
print(c)
print('\n')

# Same result obtained by NumPy's built-in broadcasting support
print('The summation of x and y:')
print(x + y)

輸出

The shape of the broadcast object:
(3, 3)


Add x and y manually using broadcast:
(3, 3)


After applying the flat function:
[[5. 6. 7.]
 [6. 7. 8.]
 [7. 8. 9.]]


The summation of x and y:
[[5 6 7]
 [6 7 8]
 [7 8 9]]
numpy_array_manipulation.htm
廣告