Home > database >  Convert csv cells to a nested list
Convert csv cells to a nested list

Time:10-13

I have a .csv file with a column which contains a list of values structured as well:

enter image description here

What I wanna do is create a nested list with all the values in the following format, so I can iterate through them with another method:

[[1009, 1310], [9420, 9699], [11590, 12009], [12290, 12499], [14460, 14809]]

I tried to read it by simple converting the cell to a list:

df = pd.read_csv('example.csv', usecols=['anomaly_sequences'])
a = df.iloc[0]['anomaly_sequences']
print(a[0])

But the output I got is: [

If I check its type with print(a.dtype) I get:

AttributeError: 'str' object has no attribute 'dtype'

How can I read it directly as a list instead of a string?

CodePudding user response:

You can use literal_eval from the standard ast library to take a string and evaluate it as python code.

import ast
df['anomaly_sequences'] = df['anomaly_sequences'].apply(ast.literal_eval)
  • Related