python - Numpy arrays containing iterable objects -
normally it's possible put arbitrary objects numpy arrays:
class foo(object): pass np.array([ foo() ]) >>> array([<__main__.foo object @ 0x10d7c3610>], dtype=object)
however, appears objects implementing __len__
, __getitem__
"unpacked" automatically:
class foo(object): def __len__(self): return 3 def __getitem__(self, i): return i*11 np.array([ foo() ]) >>> array([[0, 11, 22]])
is there way stop numpy unpacking objects in way? want put objects numpy array , have them stored objects themselves, without being unpacked. desired behavior is:
class foo(object): def __len__(self): return 3 def __getitem__(self, i): return i*11 np.array([ foo() ]) >>> array([<__main__.foo object @ 0x10d7c3610>], dtype=object)
now understand duck typing idea implies numpy should unpack looks list. perhaps it's possible mark class foo
in way tell numpy not unpack it? example, abc like:
numpy.nonenumerable.register(foo)
x = numpy.empty(appropriate_shape, dtype=object) x[:] = your_list_of_foos
for example, 1-dimensional array of 1 foo,
x = numpy.empty([1], dtype=object) x[:] = [foo()]
this has benefit of working types don't control or other parts of system may wish unpacked. example, if want list of 2 lists treated 1d array of lists,
x = numpy.empty([2], dtype=object) x[:] = [[], []]
Comments
Post a Comment