Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to create an object from each element in a python (numpy) array?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading