如何将 Pandas DataFrame 中字典的字符串表示形式转换为新列?

Sat*_*owo 2 python dictionary dataframe python-3.x pandas

我在 Pandas DataFrame Column 中有一个字典的字符串表示,如下所示:

>>> 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.}"
    ...
Run Code Online (Sandbox Code Playgroud)

我想将每个键附加到现有 DataFrame 中的列,这怎么可能?

我试过这样的事情:

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
Run Code Online (Sandbox Code Playgroud)

但我得到了 TypeError: the JSON object must be str, bytes or bytearray, not 'float'

关于如何解决这个问题的任何想法?

谢谢你。

注意:我犯了一个错误,请检查已接受的答案和评论以获取详细信息。

WeN*_*Ben 12

你可以试试 ast

df['the_column']=df['the_column'].apply(ast.literal_eval)
Run Code Online (Sandbox Code Playgroud)