How to convert string representation of dictionary in Pandas DataFrame to a new columns?

╄→尐↘猪︶ㄣ 提交于 2020-11-29 03:28:10

问题


I have a string representation of dictionary in Pandas DataFrame Column like this:

>>> df['the_column']

0 "{'a': 1., 'b': 2., 'c':3.}"
1 "{'a': 4., 'b': 5., 'c':6.}"
2 "{'a': 7., 'b': 8., 'c': 9.}"
3 "{'a': 10., 'b': 11., 'c':12.}"
    ...

I want to append each keys to columns in the existing DataFrame, how is it possible?

I have tried something like this:

list_of_new_col = [json.loads(c) for c in df['the_column']]
# resulting list of dictionary
# convert it to pandas DataFrame
# and then concat with the existing DataFrame

but I got TypeError: the JSON object must be str, bytes or bytearray, not 'float'

Any idea on how to tackle this?

Thank you.

NOTE: I made a mistake, please check accepted answer and the comment for detail.


回答1:


You can try with ast

df['the_column']=df['the_column'].apply(ast.literal_eval)


来源:https://stackoverflow.com/questions/56102724/how-to-convert-string-representation-of-dictionary-in-pandas-dataframe-to-a-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!