【问题标题】:Nesting a dictionary within another dictionary, grouping by values in a Pandas Dataframe将字典嵌套在另一个字典中,按 Pandas Dataframe 中的值分组
【发布时间】:2020-01-01 18:51:56
【问题描述】:

在上一个问题中:Nesting a counter within another dictionary where keys are dataframe columns,@Jezrael 向我展示了如何在另一个字典中嵌套一个计数器。

我的数据框有另一个列,它实际上是 ID 的超集,并且没有以允许从 ID 逻辑派生 SuperID 的方式命名。

SuperID   ID      Code
E1        E1023   a
E1        E1023   b
E1        E1023   b
E1        E1023   b
E1        E1024   b
E1        E1024   c
E1        E1024   c
E2        E1025   a
E2        E1025   a
E2        E1026   b

使用上一阶段生成的字典,

d = {k: v.value_counts().to_dict() for k, v in df.groupby('ID')['Code']}
print (d)

{'E1023': {'b': 3, 'a': 1}, 'E1024': {'c': 2, 'b': 1}, 'E1025 : {'a' : 2}, 
'E1026 : {'b' : 2}}

我想执行另一个级别的嵌套,其中 SuperID 是外部字典的键,内部字典是上面生成的字典,ID 按 SuperID 分组。所以字典实际上应该是以下格式:

new_d = {k: v for k in df.SuperID, v in df.groupby('SuperID')[ID FROM d]}

{'E1': {'E1023': {'b':3, 'a':1}, 'E1024' : {'c':2, 'b': 1}...} 'E2': {'E1025: {'a' : 2}...}}

我想保留由@Jezrael 制作的原始字典,以便我可以通过 ID 执行简单的查找,我需要在后期进行。

【问题讨论】:

    标签: python-3.x pandas dictionary pandas-groupby


    【解决方案1】:

    使用嵌套字典理解:

    d = {k: {k1: v1.value_counts().to_dict() for k1, v1 in v.groupby('ID')['Code']} 
                                             for k, v in df.groupby('SuperID')}
    print (d)
    
    {'E1': {'E1023': {'b': 3, 'a': 1}, 'E1024': {'c': 2, 'b': 1}}, 
     'E2': {'E1025': {'a': 2}, 'E1026': {'b': 1}}}
    

    【讨论】:

    • 伙计,你真是太不可思议了!这是什么魔法!?
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2016-07-24
    • 2023-04-02
    • 2022-01-02
    • 1970-01-01
    • 2013-11-16
    • 2019-04-08
    相关资源
    最近更新 更多