NumPy 中的 broadcast函数

首页 / Numpy入门教程 / NumPy 中的 broadcast函数

如前所述,NumPy具有内置的广播支持,此功能模仿广播机制,它返回一个封装了将一个数组广播到另一个数组的输出对象 。

该函数将两个数组作为输入参数。以下示例说明了其用法。

无涯教程网

import numpy as np 
x = np.array([[1], [2], [3]]) 
y = np.array([4, 5, 6])  
   
# tobroadcast x against y 
b = np.broadcast(x,y)  
# it has an iterator property, a tuple of iterators along self's "components." 

print 'Broadcast x against y:' 
r,c = b.iters 
print r.next(), c.next() 
print r.next(), c.next() 
print '\n'  
# shape attribute returns the shape of broadcast object 

print 'The shape of the broadcast object:' 
print b.shape 
print '\n'  
# to add 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'  
c.flat = [u + v for (u,v) in b] 

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

其输出如下-

Broadcast x against y:
1 4
1 5

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

从0开始学微服务 -〔胡忠想〕

如何做好一场技术演讲 -〔极客时间〕

趣谈Linux操作系统 -〔刘超〕

从0开始做增长 -〔刘津〕

安全攻防技能30讲 -〔何为舟〕

检索技术核心20讲 -〔陈东〕

Serverless入门课 -〔蒲松洋(秦粤)〕

分布式数据库30讲 -〔王磊〕

B端体验设计入门课 -〔林远宏(汤圆)〕

好记忆不如烂笔头。留下您的足迹吧 :)