New bottleneck function: replace()

13 views
Skip to first unread message

Keith Goodman

unread,
Mar 15, 2012, 3:00:15 PM3/15/12
to bottl...@googlegroups.com
I added a new function to bottleneck: bn.replace().

Replace zeros with 3 (note that the input array is modified):

>>> a = np.array([1, 2, 0])
>>> bn.replace(a, 0, 3)
>>> a
array([1, 2, 3])

Replace np.nan with 0:

>>> a = np.array([1, 2, np.nan])
>>> bn.replace(a, np.nan, 0)
>>> a
array([ 1., 2., 0.])

Some timings (this is probably not the best way to time a function
that modifies an array inplace):

I[1] a = np.random.rand(1000,1000)
I[2] a[a > 0.5] = np.nan
I[3] timeit a[np.isnan(a)] = 0
100 loops, best of 3: 2.81 ms per loop

I[4] a = np.random.rand(1000,1000)
I[5] a[a > 0.5] = np.nan
I[6] timeit mask = np.isnan(a); np.putmask(a, mask, 0)
100 loops, best of 3: 3.2 ms per loop

I[7] a = np.random.rand(1000,1000)
I[8] a[a > 0.5] = np.nan
I[9] timeit bn.replace(a, np.nan, 0)
1000 loops, best of 3: 721 us per loop

Reply all
Reply to author
Forward
0 new messages