3

I want to get the size in bytes of numerical types, in particular those defined by numpy. This is achieved by this helper function,

def sizeof(dtype):
    a = np.zeros(1, dtype=dtype)
    return int(a.nbytes)

but I was wondering if there would be a built-in, less awkward way of doing it. sys.getsizeof is of no help in this case — it returns 400 bytes for all of numpy's numeric types I have tested.

1
  • That's because that's the size of the object. Commented May 30, 2017 at 18:15

1 Answer 1

8

Use dtype.itemsize or ndarray.itemsize:

>>> import numpy as np

>>> arr = np.array([1, 2, 3], dtype=np.int32)
>>> arr.dtype.itemsize
4

>>> arr.itemsize
4
Sign up to request clarification or add additional context in comments.

5 Comments

Do you know why arr.dtype.itemsize works but say np.float32.itemsize does not?
Because it's an instance attribute - not a class attribute. np.float32().itemsize works.
So np.float32 is an extension of np.dtype, not an instance of it?
@MadPhysicist np.float32 is not a dtype it's a scalar type (that can be used as argument for the dtype parameter). dtype(np.float32) is the float32 dtype.
Interestingly, dtype(np.float32).itemsize also works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.