[英]Convert a string to Dict
I have a dataframe with several columns which i obtain from csv, which in some columns it has another dictionary.我有一个包含多列的数据框,我从 csv 获得,在某些列中它有另一个字典。 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.
现在问题从这里开始,在某些列“b”中,我有另一个字典,由于某种原因,它是字符串类型。
When i do dictionary[key]['b']
I expect to recieve a dictionary with the following format当我做
dictionary[key]['b']
我希望收到具有以下格式的字典
'{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?但是,当我执行
type(dictionary[key]['b'])
它被引用为<class 'str'>
,我如何将其转换为字典?
使用eval()
eval(dictionary[key]['b'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.