[Numpy-discussion] dtype behavior

Travis E. Oliphant oliphant at enthought.com
Thu Oct 9 11:53:27 EDT 2008


ctw wrote:
> Hi -- Can somebody here explain the following behavior:
>
> In [1]: tst = np.array([5.])
>
> In [2]: tst
> Out[2]: array([ 5.])
>
> In [3]: tst.shape
> Out[3]: (1,)
>
> In [4]: tst.dtype
> Out[4]: dtype('float64')
>
> In [5]: tst.dtype = np.int
>
> In [6]: tst
> Out[6]: array([         0, 1075052544])
>
> In [7]: tst.dtype
> Out[7]: dtype('int32')
>
> In [8]: tst.shape
> Out[8]: (2,)
>
>
>   
Setting attributes of the array always just change the information about 
the array, they never change the memory the array points to.

In this case you've taken the bits that represent float64 and 
re-interpreted them as int32 (that's why you know have a length 2 array).

So, you are exploring the floating-point bit-pattern on your computer.

If you want to "cast" to another data-type, then you need to use the 
astype method:

tst = tst.astype(np.int)

-Travis




More information about the NumPy-Discussion mailing list