【发布时间】:2020-11-27 08:36:09
【问题描述】:
import numpy as np
a = np.array([0, 10, 11, 1])
# OUT:
# array([ 0, 10, 11, 1])
b = np.arange(81).reshape(9, 9)
# OUT:
# array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
# [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
# [18, 19, 20, 21, 22, 23, 24, 25, 26],
# [27, 28, 29, 30, 31, 32, 33, 34, 35],
# [36, 37, 38, 39, 40, 41, 42, 43, 44],
# [45, 46, 47, 48, 49, 50, 51, 52, 53],
# [54, 55, 56, 57, 58, 59, 60, 61, 62],
# [63, 64, 65, 66, 67, 68, 69, 70, 71],
# [72, 73, 74, 75, 76, 77, 78, 79, 80]])
我希望 b-array 的每一项都添加到 a-array 中,并得到类似的结果,就像一个简单的循环可以做的那样:
result = list()
for row in b:
ls = list()
for i in row:
c = a + i
ls.append(c)
result.append(ls)
np.array(result)
Loop 效率不够,有什么办法可以使用 Numpy 广播规则来得到这个结果?(Numpy 数组)
【问题讨论】:
-
np.add.outer(b,a)为您提供数组。
标签: python arrays pandas numpy matrix