I have an array of numbers:
num_arr = np.array([1,2,3,4,5,6,7])
I need to transform each number into an object:
class MyObj:
def __init__(self, x):
self.val = x
What would be the best way to do that? Is there a way to do it without using loops?
>Solution :
To map over a numpy array, there is np.vectorize
class MyObj:
def __init__(self, x):
self.val = x
num_arr = np.array([1,2,3,4,5,6,7])
vfunc = np.vectorize(MyObj)
result = vfunc(num_arr)
Edit:
vectorize is not for performance but for convenience
https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.