0
例如,如果我想有條件地添加,我可以使用:使用類似的ufunc到numpy.where
y = numpy.where(condition, a+b, b)
有沒有辦法直接結合的ufunc
和where
?例如:
y = numpy.add.where(condition, a, b)
例如,如果我想有條件地添加,我可以使用:使用類似的ufunc到numpy.where
y = numpy.where(condition, a+b, b)
有沒有辦法直接結合的ufunc
和where
?例如:
y = numpy.add.where(condition, a, b)
沿着那條線的東西是add.at
。
In [21]: b = np.arange(10)
In [22]: cond = b%3==0
你where
:
In [24]: np.where(cond, 10+b, b)
Out[24]: array([10, 1, 2, 13, 4, 5, 16, 7, 8, 19])
使用其他where
(或np.nonzeros
)把布爾面具到索引記錄
In [25]: cond
Out[25]: array([ True, False, False, True, False, False, True, False, False, True], dtype=bool)
In [26]: idx = np.where(cond)
In [27]: idx
Out[27]: (array([0, 3, 6, 9], dtype=int32),)
add.at
不就地,無緩衝另外:
In [28]: np.add.at(b,idx[0],10)
In [29]: b
Out[29]: array([10, 1, 2, 13, 4, 5, 16, 7, 8, 19])
add.at
意爲讓周圍的緩衝問題與更直接的指標+=
的一種方式:
In [30]: b = np.arange(10)
In [31]: b[idx[0]] += 10
In [32]: b
Out[32]: array([10, 1, 2, 13, 4, 5, 16, 7, 8, 19])
這裏的作用是相同的(add.at
較慢)。但是如果idx
中有重複,結果會有所不同。
+=
還與布爾面膜:
In [33]: b[cond] -= 10
In [34]: b
Out[34]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
我們有了成爲ufunc
相當於+=
運營商,但我不使用ufunc
不夠了解了手。