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
广告