Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects array with numpy

are there any way to create an object form any class inside a numpy array?. Something like:

a = zeros(4)

for i in range(4):
   a[i]=Register()

Thanks

like image 650
ki0 Avatar asked Apr 20 '10 10:04

ki0


2 Answers

Yes, you can do this:

a = numpy.array([Register() for _ in range(4)])

Here, a.dtype is dtype('object').

Alternatively, if you really need to reserve memory for your array and then build it element by element, you can do:

a = numpy.empty(shape=(4,), dtype=object)
a[0] = Register()  # etc.
like image 72
Eric O Lebigot Avatar answered Oct 05 '22 04:10

Eric O Lebigot


The items in numpy arrays are statically typed, and when you call zeros you make an array of floats. To store arbitrary Python objects, use code like

numpy.array([Register() for i in range(4)])

which makes an array with dtype=object, which you could also specify manually.

Consider whether you really want numpy in this case. I don't know how close this example is to your use case, but oftentimes a numpy array of dtype object, especially a one-dimensional one, would work at least as well as a list.

like image 41
Mike Graham Avatar answered Oct 05 '22 03:10

Mike Graham