Home > Software engineering >  Convert list inside pandas dataframe to list variable
Convert list inside pandas dataframe to list variable

Time:10-03

I have a .csv file structured as well:

    chan_id   spacecraft                           anomaly_sequences
      P-1       SMAP                 [[2149, 2349], [4536, 4844], [3539, 3779]]

I need to convert the list of list inside the cell anomaly_sequences to a variable, so I can loop inside it. I did it so:

list_labels = df['anomaly_sequences'].values.tolist()

but it converted all the cell in a single list, in fact if I try to print it I see it as:

['[[2149, 2349], [4536, 4844], [3539, 3779]]']

How can I correct it?

CodePudding user response:

Not sure how you want to present your output, but if you want to convert your string into list of integers list, just do:

import json
var = "[[2149, 2349], [4536, 4844], [3539, 3779]]"
var = json.loads(var)
var

[[2149, 2349], [4536, 4844], [3539, 3779]]

And if you want to flatten the list of list, just use:

flat_list = [item for sublist in var for item in sublist]
flat_list

[2149, 2349, 4536, 4844, 3539, 3779]
  • Related