0

I have several numpy arrays containing data, and a class I defined, with attributes corresponding to each of my numpy arrays. I would like to quickly make another array containing a list of objects, with each objects attributes defined by the corresponding element of the numpy array. Basically, the equivalent of the following:

class test:
 def __init__ (self, x, y): 
 self.x = x
 self.y = y 
a = np.linspace(100)
b = np.linspace(50) 
c = np.empty(len(a), dtype = object) 
for i in range(len(a)):
 c[i] = test(a[i], b[i])

So, my question is does there exist a more concise and pythonic way to do this?

Thanks in advance!

asked Jul 23, 2016 at 20:43
0

1 Answer 1

1

That iteration is 'pythonic'.

numpy does have a function that works in this case, and may be a bit faster. It's not magical:

In [142]: a=np.linspace(0,100,10)
In [143]: b=np.linspace(0,50,10) # change to match a size
In [144]: f=np.frompyfunc(test,2,1)
In [145]: c=f(a,b)
In [146]: c
Out[146]: 
array([<__main__.test object at 0xb21df12c>,
 <__main__.test object at 0xb21dfb2c>,
 <__main__.test object at 0xb221a9cc>,
 <__main__.test object at 0xb222c44c>,
 <__main__.test object at 0xb2213d0c>,
 <__main__.test object at 0xb26bc16c>,
 <__main__.test object at 0xb2215c0c>,
 <__main__.test object at 0xb221598c>,
 <__main__.test object at 0xb21eb2cc>,
 <__main__.test object at 0xb21ebc6c>], dtype=object)
In [147]: c[0].x,c[1].y
Out[147]: (0.0, 5.555555555555555)

frompyfunc returns a function that applies the input f to elements of a,b. I define it as taking 2 inputs, and returning 1 array. By default it returns an object array, which suits your case.

np.vectorize uses this same function, but with some overhead that can make it easier to use.

It also handles broadcasting, so by changing an input into a column array I get a 2d output:

In [148]: c=f(a,b[:,None])
In [149]: c.shape
Out[149]: (10, 10)

But keep in mind that there isn't a lot that you can do with this c. It's little more a list of test instances. For example c+1 does not work, unless you define a __add__ method.

answered Jul 23, 2016 at 20:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.