如何将Pandas DataFrame中字典的字符串表示形式转换为新列? [英] How to convert string representation of dictionary in Pandas DataFrame to a new columns?

查看:51
本文介绍了如何将Pandas DataFrame中字典的字符串表示形式转换为新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Pandas DataFrame列中有一个字典的字符串表示形式,

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.}"
    ...

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

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

我尝试过这样的事情:

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

但是我明白了 TypeError:JSON对象必须为str,字节或字节数组,而不是"float"

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

Any idea on how to tackle this?

谢谢.

注意:我错了,请检查接受的答案和评论以获取详细信息.

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

推荐答案

您可以尝试使用 ast

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

这篇关于如何将Pandas DataFrame中字典的字符串表示形式转换为新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆