northerner northerner - 2 months ago 8
Python Question

Convert all 2D array (list) elements to float

I have the following list:

[['0', '2', '4', '10'], ['2', '0', '2', '9'], ['4', '2', '0', '12'], ['10', '9', '12', '0']]


My wish is to convert each element into float.

My work

Initially, I tried converting a simple list ...

my_list = ['1','2','5','7']


.. by creating a new list and casting to float, with the following:

my_list = ['1','2','5','7']
new_list = []
for item in my_list:
new_list.append(float(item))


However, the problem arises when trying to do the same for nested lists, as is the case for my actual list.

I have tried the following:

my_list2 = [['1','2'],['5','7']]
new_list = []
for row in my_list2:
for col in row:
new_list.append(float(col))


However, this eliminates the nested list structure, giving me:

[1.0, 2.0, 5.0, 7.0]


And not preserving the original separations, like:

[[1.0, 2.0], [5.0, 7.0]]


Any help is highly appreciated!

Answer

try this for loop:

my_list = [['0', '2', '4', '10'], ['2', '0', '2', '9'], ['4', '2', '0', '12'], ['10', '9', '12', '0']]
for i, el in enumerate(my_list):
    my_list[i] = map(float, el)

a more elegant and performant way is to convert in a numpy.array

import numpy as np
my_list = [['0', '2', '4', '10'], ['2', '0', '2', '9'], ['4', '2', '0', '12'], ['10', '9', '12', '0']]
array = np.asarray(my_list, dtype=float)