Alex Savin Alex Savin - 1 month ago 9
Python Question

How to create a list of lists of integers from DataFrame?

I have Data Frame:

Values Values2
1,2,3,4 0,2,3
2,1,0,6 0,0,0
9,8,7,6 1,0,1


I want to create list of lists. I do that in following way:

df[['Values']].values.tolist()


In output a get:

[['1,2,3,4'],
['2,1,0,6'],
['9,8,7,6']]


It's a strings but I need a lists of integer like that:

[[1,2,3,4],
[2,1,0,6],
[9,8,7,6]]


How can I do that?

Answer

It seems they are stored as a string. Try the following (not very robust, but depending on your context it can be ok):

slist = df[['Values']].values.tolist()
ilist = [ [int(s) for s in l[0].split(',')] for l in slist]