0

I have a dataframe with several columns which i obtain from csv, which in some columns it has another dictionary. I then proceed to do the following

df = df.set_index('case_id')
dictionary = df.to_dict('index')
list = list(dictionary.keys())
df = df.reset_index()

All perfect to here, I obtain the dictionary as expected with the index as it's key. Now the problem starts here, In some column "b" I have another dictionary which for some reason is type string.

When i do dictionary[key]['b'] I expect to recieve a dictionary with the following format

'{0: [datetime.datetime(2018, 9, 3, 13, 41, 37), 1162.0], 1: [datetime.datetime(2018, 9, 3, 14, 0, 59), 347.0], 2: [datetime.datetime(2018, 9, 3, 14, 6, 46), 1719.0], 3: [datetime.datetime(2018, 9, 3, 14, 35, 25), 14.0], ... }'

However when I do type(dictionary[key]['b']) it is referenced as <class 'str'>, how can I transform this as to a dictionary?

  • 1
    Hi Jose - would you take a moment to please read https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples ? and [edit] your Q accordingly? – Jon Clements Mar 18 '20 at 15:11
  • How did this string get into the dataframe in the first place? – chepner Mar 18 '20 at 15:11

1 Answers1

1

Use eval()

eval(dictionary[key]['b'])
jjsantoso
  • 1,586
  • 1
  • 12
  • 17