stchlk
stchlk

Reputation: 156

extract a list of tuples from pandas series stored as string

I have a csv that I've read into pandas with the following format

import pandas as pd

data = [['A', "[('a', 1), ('b', 2)]"], ['C', "[('c', 3), ('d', 4)]"]] 

mydf = pd.DataFrame(data, columns = ['name', 'tupledat'])

how can I extract values from the second column as a list of tuples? I think this may have been generated as a multiindex? I'm not very familiar with that concept. Can this be specified when reading in from csv with pandas? I have struggled to accomplish this by string-splitting. I think there must be a ready-made solution for this common scenario.

example desired result: [('a', 1), ('b', 2)]

Upvotes: 0

Views: 366

Answers (1)

BENY
BENY

Reputation: 323286

Check with ast

import ast 
df.tupledat=df.tupledat.apply(ast.literal_eval)
df
Out[59]: 
  name          tupledat
0    A  [(a, 1), (b, 2)]
1    C  [(c, 3), (d, 4)]

Upvotes: 2

Related Questions