I have a 2d numpy array, with shape (100,3)
a = np.random((100,3))
and I want to call a function fun
:
b = fun(a)
This function is currently defined:
@np.vectorize
def fun(r):
if r <= 0.0: return 0.0
else: return min(2.0/(1.0 + r), 2.0*r/(1.0 + r))
and this works fun. But I would like to express this in a more numpythonic (and therefore more efficient) way. I tried:
def fun(r):
ans = zeros_like(r)
ans[r > 0.0] = min(2.0/(1.0 + r), 2.0*r/(1.0 + r))
return ans
but that don't work as the min
is not doing what I want. I also tried:
def fun(r):
return np.piecewise(r
, [r <= 0.0, r > 0.0]
, [0.0, lambda x: min(2.0/(1.0 + x), 2.0*x/(1.0 + x))]
)
but that doesn't work for a similar reason. So how should I do it?
min
,np.min
andnp.minimum
. In this case, it looks like you wantnp.minimum
. $\endgroup$np.min
would find the min of the whole array, which is the incorrect behaviour.np.minimum
might be the correct one to use, but it saysValueError: array is not broadcastable to correct shape
. $\endgroup$np.minimum(2./(1.+r),2.*r/(1.+r))
works for me; the problem is with the assignment:ans[r>0]
returns all entries where r is nonzero as an 1d array. How about(r>0)*np.minimum(...)
? $\endgroup$