If I wanted to apply a function row-wise (or column-wise) to an ndarray, do I look to ufuncs (doesn’t seem like it) or some type of array broadcasting (not what I’m looking for either?) ?
Edit
I am looking for something like R’s apply function. For instance,
apply(X,1,function(x) x*2)
would multiply 2 to each row of X through an anonymously defined function, but could also be a named function. (This is of course a silly, contrived example in which apply is not actually needed). There is no generic way to apply a function across an NumPy array’s “axis”, ?
First off, many numpy functions take an
axisargument. It’s probably possible (and better) to do what you want with that sort of approach.However, a generic “apply this function row-wise” approach would look something like this:
Keep in mind that we can do exactly the same thing with just:
There’s often a better way that the generic approach, especially with numpy.
Edit:
I completely forgot about it, but the above is essentially equivalent to
numpy.apply_along_axis.So, we could re-write that as: