Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 with NumPy and object references

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.

like image 756
andreSmol Avatar asked Sep 28 '26 20:09

andreSmol


2 Answers

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
like image 108
unutbu Avatar answered Sep 30 '26 10:09

unutbu


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.

like image 40
Petr Viktorin Avatar answered Sep 30 '26 12:09

Petr Viktorin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!