首页 > 解决方案 > 使用字典键作为标题将字典数据从数据帧列获取到新的数据帧

问题描述

我有一个数据框,其中一列充满了字典:

                  Col
Index1   {"A":1, "B":2, "C":3}
Index2   {"A":4, "B":5, "C":6}
.
.
.

我想要一个新的数据框:

          A    B    C
Index1    1    2    3 
Index2    4    5    6
.
.
.

如您所见,DF 列中的 dict 键应该成为新的标题。理想情况下,我想保留索引。

我试图用这个from_dict从该列创建一个新的数据框,但它不起作用。

IE

new_DF = pd.DataFrame.from_dict(old_DF[Col])

我得到了错误:ValueError: If using all scalar values, you must pass an index

我也尝试了其他方法无济于事。任何指导将不胜感激。

标签: python-3.xpandas

解决方案


apply与 一起使用pd.Series

>>> df['Col'].apply(pd.Series)
        A  B  C
Index1  1  2  3
Index2  4  5  6
>>> 

或使用pd.json_normalize

>>> pd.json_normalize(df['Col']).set_axis(df.index)
        A  B  C
Index1  1  2  3
Index2  4  5  6
>>> 

或尝试添加tolist

>>> pd.DataFrame(df['Col'].tolist(), index=df.index)
        A  B  C
Index1  1  2  3
Index2  4  5  6
>>> 

编辑:

如果您的列是字符串类型,请尝试:

from ast import literal_eval
df['Col'].map(literal_eval).apply(pd.Series)

        A  B  C
Index1  1  2  3
Index2  4  5  6

推荐阅读