提问人:Gabriel Vasconcelos Fruet 提问时间:2/3/2023 更新时间:2/3/2023 访问量:69
numpy m x n 组合网格与 m 和 n 数组
numpy m x n combination grid with m and n array
问:
我想知道是否有一种简单的方法可以做到这一点:
a =
[[1,2],[3,4]]
b =
[[5,6],[7,8],[9,10]]
变成这样:
c =
[[[1,2], [1,2], [1,2]],
[[3,4], [3,4], [3,4]]]
d =
[[[5,6], [7,8], [9,10]],
[[5,6], [7,8], [9,10]]]
所以我可以这样做:
c - d
我已经尝试过使用 np.meshgrid,但它真的很笨拙:
indexes_b, indexes_a = np.meshgrid(
np.arange(a.shape[0]),
np.arange(b.shape[0])
)
c = a[indexes_a]
d = b[indexes_b]
c - d # works
答:
0赞
Jônathan Dambros
2/3/2023
#1
试试这个:
a = [[1,2],[3,4]]
b = [[5,6],[7,8],[9,10]]
c = [[li]*len(b[0]) for li in a]
d = [[li]*len(a) for li in b]
print(c)
print(d)
评论
4赞
Corralien
2/3/2023
#2
用:broadcasting
>>> a[:, None] - b
array([[[-4, -4],
[-6, -6],
[-8, -8]],
[[-2, -2],
[-4, -4],
[-6, -6]]])
>>> c - d
array([[[-4, -4],
[-6, -6],
[-8, -8]],
[[-2, -2],
[-4, -4],
[-6, -6]]])
评论
0赞
mozway
2/3/2023
我也在计算实数,以防万一也需要:c
d
c = np.tile(a[:,None], (1,b.shape[0],1)) ; d = np.tile(b[None], (a.shape[0],1,1))
评论
np.subtract.outer(a,b)
或a[None]-b[:,None]