pandas 数据框中的字典列 [英] Dictionary column in pandas dataframe

查看:79
本文介绍了 pandas 数据框中的字典列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv,我正在将其读入pandas数据框.但是,其中一列是字典的形式.这是一个示例:

I've got a csv that I'm reading into a pandas dataframe. However one of the columns is in the form of a dictionary. Here is an example:

ColA, ColB, ColC, ColdD
20, 30, {"ab":"1", "we":"2", "as":"3"},"String"

如何将其转换为如下所示的数据框:

How can I turn this into a dataframe that looks like this:

ColA, ColB, AB, WE, AS, ColdD
20, 30, "1", "2", "3", "String"

编辑 我解决了这个问题,它看起来像这样,但是它是一个需要解析的字符串,而不是dict对象.

edit I fixed up the question, it looks like this but is a string that needs to be parsed, not dict object.

推荐答案

按照 https://stackoverflow.com/a/38231651 /454773 ,您可以使用.apply(pd.Series)将包含dict的列映射到新列,然后将这些新列连接回到原始数据框中,减去包含dict的原始列:

As per https://stackoverflow.com/a/38231651/454773, you can use .apply(pd.Series) to map the dict containing column onto new columns and then concatenate these new columns back into the original dataframe minus the original dict containing column:

dw=pd.DataFrame( [[20, 30, {"ab":"1", "we":"2", "as":"3"},"String"]],
                columns=['ColA', 'ColB', 'ColC', 'ColdD'])
pd.concat([dw.drop(['ColC'], axis=1), dw['ColC'].apply(pd.Series)], axis=1)

返回:

ColA    ColB    ColdD   ab  as  we
20      30      String  1   3   2

这篇关于 pandas 数据框中的字典列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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