I need to create a large matrix (array) structure (3 axis) and each element should store the reference to a Python object (myclass instance). Is it possible to use numpy to create such an array. Which data type should I use in order to store Python references? The advantage of numpy is the support of slicing at different levels. The alternativee is to create a nested (nested) list but it is a cumbersome solution.
Use dtype=object to store Python objects in the array.
import numpy as np
class Foo: pass
arr=np.empty(2,dtype=object)
arr[:]=[Foo(),Foo()]
print(arr)
# [<__main__.Foo instance at 0xb7827d0c>
# <__main__.Foo instance at 0xb748b5ac>]
print(arr.dtype)
# object
Just give object as the dtype, and you can store anything you want.
import numpy
print numpy.array([['a', (2, 2)], [1, 2+3j], [open, xrange(7)]], dtype=object)
Any unrecognized type will work this way, so you might want to use myclass instead of object. object just makes it clear that you'll be storing arbitrary objects without any numpy optimization. See the docs for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With