首页 > 解决方案 > 将熊猫 PrettyDict 转换为字典

问题描述

我有一个熊猫数据框df:

pd.DataFrame({'col1': ["a", "x", "g", "y", "q", "n"],
              'col2': ["b", "f", "s", "p", "t", "c"],
              'col3': [1, 10, 1, 1, 10, 2]}
)

>
    col1  col2  col3 
0    a     b     1
1    b     f     10
2    g     s     1
3    y     p     1
4    q     t     10
5    1     0     2

我根据 col3 对其进行分组:

grp = df.groupby(["col3"])
groups = grp.groups

但结果是一个有pandas.io.formats.printing.PrettyDict类型的对象。有什么办法可以将它转换为普通字典吗?

标签: pandasdataframepandas-groupby

解决方案


PrettyDict 源代码如下:

class PrettyDict(Dict[_KT, _VT]):
    """Dict extension to support abbreviated __repr__"""

    def __repr__(self) -> str:
        return pprint_thing(self)

实际上,我们可以看到这groups是一个普通的字典

grp = df.groupby(["col3"])
groups = grp.groups

推荐阅读