Suppose I have a NumPy structured array with various numeric datatypes. As a basic example,
my_data = np.array( [(17, 182.1), (19, 175.6)], dtype='i2,f4')
How can I cast this into a regular NumPy array of floats?
From this answer, I know I could use
np.array(my_data.tolist())
but apparently it is slow since you "convert an efficiently packed NumPy array to a regular Python list".
Here's one way (assuming
my_data
is a one-dimensional structured array):A variation on Warren's answer (which copies data by field):
Or you could iterate by row.
r
is a tuple. It has to be converted to a list in order to fill a row ofx
. With many rows and few fields this will be slower.It may be instructive to try
x.data=r.data
, and get an error:AttributeError: not enough data for array
.x
data is a buffer with 4 floats.my_data
is a buffer with 2 tuples, each of which contains an int and a float (or sequence of [int float int float]).my_data.itemsize==6
. One way or other, themy_data
has to be converted to all floats, and the tuple grouping removed.But using
astype
as Jaime shows does work:In quick tests using a 1000 item array with 5 fields, copying field by field is just as fast as using
astype
.You can do it easily with Pandas:
The obvious way works: