1
votes

I have a numpy list, type of its element is numpy.float64 and I would like to convert all element of the list to float.

This is the print out of the list:

[array([ -7.19244777e+24,   3.32768299e-02,  -7.19249216e+24], dtype=float32), 
 array([ -8.87044985e+25,   1.46775544e-01,  -8.87068228e+25], dtype=float32), 
 array([ 0.61927807, -0.16575921,  0.98002648], dtype=float32),
 array([ 0.63426137, -0.15838303,  0.97730571], dtype=float32)]

I could convert each element from numpy.float to float with following code.

mtx = []
for i in range(len(centroids)):
    row = []
    for j in range(len(centroids[i])):
        row.append(np.asscalar(centroids[i][j])) 
    mtx.append(row) 

I am wondering is there any one-liner or utility method to convert elements of whole list from numpy.float64 to float ?

Same question for string and other data types.

1
np.asarray(centroids, dtype=float)? - N. Wouda
I fear the cause of this in the first place is that your lists are ragged (not equal sized in length), unless these are all the arrays you have. - cs95

1 Answers

5
votes

np.ndarray.tolist() does precisely what you want.

>>> a = np.identity(3, np.float64)
>>> a
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
>>> a.dtype
dtype('float64')
>>> b = a.tolist()
>>> type(b[0][0])
<class 'float'>

Applied to your list of arrays:

>>> array = np.array
>>> float32 = np.float32
>>> loa = [array([ -7.19244777e+24,   3.32768299e-02,  -7.19249216e+24], dtype=float32), 
...  array([ -8.87044985e+25,   1.46775544e-01,  -8.87068228e+25], dtype=float32), 
...  array([ 0.61927807, -0.16575921,  0.98002648], dtype=float32),
...  array([ 0.63426137, -0.15838303,  0.97730571], dtype=float32)]
>>> 
>>> lol = [a.tolist() for a in loa]
>>> lol
[[-7.192447772100603e+24, 0.03327682986855507, -7.19249215957853e+24], [-8.870449851573768e+25, 0.14677554368972778, -8.870682280549097e+25], [0.619278073310852, -0.16575920581817627, 0.9800264835357666], [0.6342613697052002, -0.15838302671909332, 0.9773057103157043]]
>>> type(lol[0][0])
<class 'float'>