Argo Argo - 1 month ago 7
Python Question

Change string to integer in all lists inside a list using Python

I got this:

X = [['0.4,0,6'],['0.2,0,3'],['0.1,0,8']]


And I want to achieve this:

X = [[0.4,0,6],[0.2,0,3],[0.1,0,8]]


I need to make that change because it's causing me a ValueError:

array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: invalid literal for float(): 0.1,0,8


Does anyone have any idea how to make that change?

Answer

You have strings in those sublists, which makes it a little confusing. You'll need to split them before converting each item to float:

>>> [[float(i) for i in lst[0].split(',')] for lst in X]
[[0.4, 0.0, 6.0], [0.2, 0.0, 3.0], [0.1, 0.0, 8.0]]