Nils Werner
Nils Werner

Reputation: 36765

Information about dtype of array

I know numpy has methods numpy.finfo() for information about a float-based dtype and numpy.iinfo() for its integer counterpart. Is there a method that accepts any dtype? Currently I am forced to pick the right one myself:

try:
    maxv = numpy.finfo(data.dtype).max
except:
    maxv = numpy.iinfo(data.dtype).max

Upvotes: 0

Views: 92

Answers (2)

H.D.
H.D.

Reputation: 4454

For "any" type I'm pretty sure there's no such method, as that's not a general information.

In [7]: np.array([], dtype=object).dtype.itemsize
Out[7]: 8

That's an object, generally. Each cell of such an array requires a storage size that can store a memory address. It might reference a Python long, for example, but probably that's not the kind of task you'd use NumPy for.

Be careful: Python long casts to int64 unless it's big enough to need more than 64 bits!

In [11]: np.array([long(123)]).dtype
Out[11]: dtype('int64')

In [12]: np.array([123456789 ** 1234]).dtype
Out[12]: dtype('object')

You can get the information if it's a "float" or "integer" from the kind attribute

In [14]: np.array([123456789 ** 1234]).dtype.kind
Out[14]: 'O'

In [15]: np.array([long(123)]).dtype.kind
Out[15]: 'i'

In [16]: np.array([2.3, 4.3]).dtype.kind
Out[16]: 'f'

You can get it from NumPy by name:

{"i": np.iinfo, "f": np.finfo}[data.dtype.kind](data.dtype).max

Upvotes: 0

unutbu
unutbu

Reputation: 879531

I don't think NumPy provides such a function. Just define the function yourself, put it in a module, and import it as necessary. Note that in general using bare except is a bad practice. Using except ValueError here would be better.

Upvotes: 2

Related Questions