user545424
user545424

Reputation: 16179

numpy array of python objects

Since when did numpy allow you to define an array of python objects? Objects array with numpy.

Is there any fundamental difference between these arrays and a python list?

What is the difference between these arrays and say, a python tuple?

There are several handy numpy functions I would like to use, i.e. masks and element-wise operations, on an array of python objects and I would like to use them in my analysis, but I'm worried about using a feature I can't find documentation for anywhere. Is there any documentation for this 'object' datatype?

Was this feature was added in preparation for merging numpy into the standard library?

Upvotes: 6

Views: 9414

Answers (1)

Fred Foo
Fred Foo

Reputation: 363577

The "fundamental" difference is that a Numpy array is fixed-size, while a Python list is a dynamic array.

>>> class Foo:
...  pass
... 
>>> x = numpy.array([Foo(), Foo()])
>>> x.append(Foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'

(You can get around this with numpy.concatenate, but still Numpy arrays aren't meant as a drop-in replacement for list.)

Arrays of object are perfectly well documented, but be aware that you'll have to pass dtype=object sometimes:

>>> numpy.array(['hello', 'world!'])
array(['hello', 'world!'], 
      dtype='|S6')
>>> numpy.array(['hello', 'world!'], dtype=object)
array(['hello', 'world!'], dtype=object)

Upvotes: 9

Related Questions