[Numpy-discussion] Behavior from a change in dtype?
Mon Sep 7 19:01:18 CDT 2009
On Mon, Sep 7, 2009 at 7:35 PM, <email@example.com> wrote:
> On Mon, Sep 7, 2009 at 6:36 PM, Skipper Seabold<firstname.lastname@example.org> wrote:
>> Hello all,
>> I ran into a problem with some of my older code (since figured out the
>> user error). However, in trying to give a simple example that
>> replicates the problem I was having, I ran into this.
>> In : a = np.array((1.))
>> In : a
>> Out: array(1.0)
>> # the dtype is 'float64'
>> In : a.dtype='<i8'
> The way I understand it is:
> Here you are telling numpy to interpret the existing memory/data in a
> different way, which might make sense or not depending on the types,
> e.g. I also used this to switch between structured arrays and regular
> arrays with compatible memory. However it does not convert the data.
> If you want to convert the data to a different type, numpy needs to
> create a new array, e.g. with astype
>>>> a = np.array((1.))
>>>> b = a.astype('<i8')
> array(1L, dtype=int64)
Hmm, okay, well I came across this in trying to create a recarray like
data2 below, so I guess I should just combine the two questions. Is
the last example the best way to do what I'm trying to do (taken from
an old thread)? I would like to add a few more examples of best
practice here <http://docs.scipy.org/doc/numpy/user/basics.rec.html>,
so I don't need to go looking again.
import numpy as np
data = np.array([[10.75, 1, 1],[10.39, 0, 1],[18.18, 0, 1]])
dt = np.dtype([('var1', '<f8'), ('var2', '<i8'), ('var3', '<i8')])
data2 = data.copy()
data3 = data.copy()
# Doesn't work, raises TypeError: expected a readable buffer object
data2 = data2.view(np.recarray)
# Works without error (?) with unexpected result
data3 = data3.view(np.recarray)
data3.dtype = dt
# One correct (though IMHO) unintuitive way
data = np.rec.fromarrays(data.swapaxes(1,0), dtype=dt)
More information about the NumPy-Discussion