Home > Back-end >  Pandas convert column where every cell is list of strings to list of integers
Pandas convert column where every cell is list of strings to list of integers

Time:05-17

I have a dataframe with columns that has list of numbers as strings:

C1 C2 l
1   3 ['5','9','1']
7   1 ['7','1','6']

What is the best way to convert it to list of ints?

C1 C2 l
1   3 [5,9,1]
7   1 [7,1,6]

Thanks

CodePudding user response:

Pandas' dataframes are not designed to work with nested structures such as lists. Thus, there is no vectorial method for this task.

You need to loop. The most efficient is to use a list comprehension (apply would also work but with much less efficiency).

df['l'] = [[int(x) for x in l] for l in df['l']]

NB. There is no check. If you have anything that cannot be converted to integers, this will trigger an error!

Output:

  C1 C2         l
0  1  3 [5, 9, 1]
1  7  1 [7, 1, 6]

CodePudding user response:

You can try

df['l'] = df['l'].apply(lambda lst: list(map(int, lst)))
print(df)

   C1  C2          l
0   1   7  [5, 9, 1]
1   3   1  [7, 1, 6]
  • Related