Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easy way of getting number of bits from a numpy type? [duplicate]

Is there an easy way to get the number of 8-bit bytes that corresponds to a particular numpy type?

I know I can do this:

lookup = {np.uint8:   1, np.int8:   1,
          np.uint16:  2, np.int16:  2, 
          np.uint32:  4, np.int32:  4,
          np.uint64:  8, np.int64:  8}
def getByteSize(dtype):
   return lookup[dtype]

but this seems slightly kludgey and it seems like there ought to be a built-in method of retrieving this info.

like image 878
Jason S Avatar asked Oct 25 '13 21:10

Jason S


People also ask

How do you extract all numbers between a given range from a NumPy array?

Using the logical_and() method The logical_and() method from the numpy package accepts multiple conditions or expressions as a parameter. Each of the conditions or the expressions should return a boolean value. These boolean values are used to extract the required elements from the array.

How can you identify the datatype of a given NumPy array?

Creating numpy array by using an array function array(). This function takes argument dtype that allows us to define the expected data type of the array elements: Example 1: Python3.

What is NumPy float32?

float32. Single precision float: sign bit, 8 bits exponent, 23 bits mantissa.


1 Answers

You can use the nbytes attribute of an instance of the type:

In [8]: np.uint8(0).nbytes
Out[8]: 1

In [9]: np.uint16(0).nbytes
Out[9]: 2

In [10]: np.uint32(0).nbytes
Out[10]: 4

etc.

You can drop the argument (0 is assumed), and you can also use the itemsize attribute instead of nbytes:

In [13]: np.int32().itemsize
Out[13]: 4

A method that (apparently) avoids creating an instance of the numeric type is to create a dtype object, and then access its itemsize attribute (but I doubt this is going to be more memory or time efficient than simply creating an instance of the numeric type):

In [14]: dt = np.dtype(np.int32)

In [15]: dt.itemsize
Out[15]: 4

(I said "apparently" because I haven't looked at the source code for dtype. For all I know, it might create an instance of its argument.)

like image 166
Warren Weckesser Avatar answered Nov 14 '22 21:11

Warren Weckesser