給定兩個一維 numpy 陣列:
>>> a = np.arange(10)
>>> b = np.arange(2)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
array([0, 1])
如何添加它們,以便將 的值b添加到 的值中,a就好像b重復了五次?這種事情在 R 中是自動的,但在 Numpy 中似乎不是:
>>> a b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (10,) (2,)
我能想到的最好方法是平鋪b以使其大小合適,但這看起來很笨重(尤其是整數除法......):
>>> a np.tile(b, a.shape[0]//b.shape[0])
array([ 0, 2, 2, 4, 4, 6, 6, 8, 8, 10])
假設的長度b除以 的長度a,是否有更好的解決方案?
uj5u.com熱心網友回復:
一種替代解決方案是使用隱式廣播:
(a.reshape(-1, b.shape[0]) b).reshape(-1)
請注意,重塑操作很便宜(沒有復制)。請注意,它a.shape[0]仍然必須b.shape[0]像基于 tile 的解決方案一樣被整除。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368780.html
上一篇:c 指標賦值問題
