Raj
Raj

Reputation: 3462

numpy convert 2D Integer Record to 2D floating point Record

I want to convert the record [(1, 2, 3) (2, 2, 3)] which is of integer type to floating type array as [(1.0, 2.0, 3.0), (2.0, 2.0, 3.0)]. However when I give the command c.astype('float') what I get at the output is rec.array([ 1., 2.]). Why the other elements are deleted from the array?

Could someone please give me the correct solution? Am I doing it the right way?

Update I created the record from 3 different arrays like this - d=np.rec.fromarrays([a, b, c], names='x,y,z') in order to sort them and do some operations.

Here is the complete code -

a=[1,2]
b=[2,2]
c=[3,3]
d=np.rec.fromarrays([a, b, c], names='x,y,z')
print d
d.astype('float')
print d

Upvotes: 2

Views: 5809

Answers (3)

DSM
DSM

Reputation: 353499

Inelegant but (apparently) working:

In [23]: import numpy as np

In [24]: a=[1,2]

In [25]: b=[2,2]

In [26]: c=[3,3]

In [27]: d=np.rec.fromarrays([a, b, c], names='x,y,z')

In [28]: d
Out[28]: 
rec.array([(1, 2, 3), (2, 2, 3)], 
      dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')])

In [29]: d.astype([(k, float) for k in d.dtype.names])
Out[29]: 
rec.array([(1.0, 2.0, 3.0), (2.0, 2.0, 3.0)], 
      dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

Upvotes: 3

mgilson
mgilson

Reputation: 310227

Hmmm... the only way I can coax it is:

a = np.rec.array([(1,2,3)])
np.array(list(a[0]),dtype='float')

for a N dimensional array:

a = np.array(map(list,d),dtype='float')

Hopefully someone else will come along with a better way...

Upvotes: 1

eumiro
eumiro

Reputation: 213075

>>> np.array([(3, 0, 1)]).astype('float')
array([[ 3.,  0.,  1.]])

Does your code look different?

Upvotes: 3

Related Questions