pandas - 将熊猫 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
类型的对象。有什么办法可以将它转换为普通字典吗?
解决方案
类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
推荐阅读
- sql-server - SQL Server 分组填充月差
- reactjs - symfony 5 web 调试工具栏显示匿名并且在 onAuthenticationSuccess 后无法重定向
- excel - 如何使用变量范围跨工作表复制和粘贴?
- deep-learning - 重用pytorch模型时重复层
- blazor - 如何将 cshtml 与 _layout.razor 连接
- node.js - 从 git 子模块运行嵌套的 vscode launch.json
- sql - SQL INNER JOIN 机制
- spring - 分析未在 gradle 中发生
- r - ifelse calc 在控制台中正确显示,但在 R 中的数据框中不正确显示
- drake - PyDrake ComputePointPairPenetration() 杀死内核