0
votes

I've started using NumPy lately (and it is really useful so far -- why didn't I start using it sooner?), but there are still a few things which I'm sure I'm doing wrong:

  • How do you apply a function to a vector (ndarray)? I'd like it to be vectorized, and its a more complex function than just multiplication. I've tried using np.where, but that just seems to be an ugly solution (and I'm not sure if its vectorized either). Is there a function similar to map such that my function would be vectorized?

  • Suppose I have a two-dimensional array -- just an array of 2d position vectors, and suppose I want to find the norm of each vector, and if it is over a certain value, do whatever. np.where seems to be a great solution for this but it won't work unless I transpose the array: np.where(sum(a.T**2) > 10, a * 2, 0) (Just an arbitrary example). This really seems verbose and the transpose doesn't make much sense.

  • Finally, if I have a three-dimensional array - a two dimensional array of 2d position vectors (such that at position [1, 2] would be the vector (1, 2)). How can I iterate through all of the vectors (with a vectorized function such as np.where)? I've been using np.reshape, but I'd like to keep the array the same shape if possible.

I grouped these questions together because they seem similar, but if I need to split them into separate threads, please let me know and I'll do so.

1
While there are ways to do the things you describe, you might check out pandas which is set up to handle many of these operations. - Jeff Tratner
what do you mean by your first question? You can, obviously, chain multiple arithmetic and other operators together to build a larger function. Otherwise, if you wanted to vectorize your function, you'd need to drop into C or Fortran (or Cython), because there's no way for numpy to bypass the expense of a function call on every element. - Jeff Tratner
I can't, though, say, for example, create a new numpy array from each element sum it? (just an example, I wouldn't just be summing it). - James
I'm still unclear on what you're asking. You should post some example inputs and outputs to demonstrate what you mean. Also, I really suggest you check out pandas or numba first, because they might get you to a workable solution (and require very little effort). - Jeff Tratner

1 Answers

0
votes

Like the comments above, I'm not quite sure what you are asking. But for the first question, take this example:

Say you have a numpy array of 2d vectors and you want to calculate the norm of each vector. Couldn't you do something like:

import numpy as np

x = np.arange(20).reshape(10,2)
norm_func = lambda z: sum(z**2)
norm_func(x.T)

This would give the result

array([ 1,  5,  9, 13, 17, 21, 25, 29, 33, 37])

for the array

array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17],
       [18, 19]])