问题
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