pythonnumpy

Size of data type using NumPy


In NumPy, I can get the size (in bytes) of a particular data type by:

datatype(...).itemsize

or:

datatype(...).nbytes

For example:

np.float32(5).itemsize # 4
np.float32(5).nbytes   # 4

I have two questions. First, is there a way to get this information without creating an instance of the datatype? Second, what's the difference between itemsize and nbytes?


Solution

  • You need an instance of the dtype to get the itemsize, but you shouldn't need an instance of the ndarray. (As will become clear in a second, nbytes is a property of the array, not the dtype.)

    E.g.

    np.dtype(float).itemsize      # 8
    np.dtype(np.float32).itemsize # 4
    np.dtype('|S10').itemsize     # 10
    

    As far as the difference between itemsize and nbytes, nbytes is just x.itemsize * x.size.

    E.g.

    np.arange(100).itemsize # 8
    np.arange(100).nbytes   # 800