在另一个字典中嵌套一个计数器,其中的键是数据框列 [英] Nesting a counter within another dictionary where keys are dataframe columns

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

问题描述

我有一个Pandas数据框,格式如下:

I have a Pandas dataframe with a format like:

    ID      Code
    E1023   a
    E1023   b
    E1023   b
    E1023   b
    E1024   b
    E1024   c
    E1024   c

我想创建一个字典,将ID列作为键,将Code列中的值及其特定ID的计数嵌套在其中:

I would like to create a dictionary with the ID column as a key, with values from the Code column and its counts for a particular ID nested inside like:

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

我知道我可以在代码列上使用计数器,但是该怎么做我这样做是按照ID将其分组,然后嵌套在ID为键的字典中?

I understand that I can use a Counter on the Code column, but how do I do this such that it is grouped by the ID and then nested within a dictionary where the ID is key?

推荐答案

使用字典 DataFrame理解。 groupby Series.value_counts Series.to_dict

Use dictionary comprehension with DataFrame.groupby and Series.value_counts with Series.to_dict:

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}}

或使用 Counter ,然后转换为 dict

from collections import Counter
d = {k: dict(Counter(v)) for k, v in df.groupby('ID')['Code']}

这篇关于在另一个字典中嵌套一个计数器,其中的键是数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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