python - 如何从 pandas Dataframe groupby 对象中获取一系列 json/字典
问题描述
我有一个超过 2 列(Col1、Col2 等)的数据框,我想生成一个索引为 Col1 的系列,并且系列的值是字典,其中键是 Col2,值(的dict) 是元组 (Col1, Col2) 的出现次数。
假设数据框是这样的:
Col1 Col2 Col3 ...
0 A b ...
1 B e ...
2 A a ...
3 C a ...
4 A b ...
5 B c ...
6 A e ...
7 B c ...
我想要的输出是:
A {'a':1,'b':2,'e':1}
B {'c':2,'e':1}
C {'a':1}
我通过这个循环设法做到了:
for t in my_df['Col1'].unique():
my_series.loc[t] = my_df[my_df['Col1'] == t].groupby('Col2').size().to_json()
但我想知道是否有一种方法可以使用 pandas 方法更有效地做到这一点,而无需迭代。
我还尝试使用两个索引进行 groupby:
my_df.groupby(['Col1','Col2']).size()
>
Col1 Col2
A a 1
b 2
e 1
B c 2
e 1
C a 1
但找不到下一步将结果转换为 dict 的系列,如上图所示
解决方案
你需要一个 defaultdict:
import collections
resul = collections.defaultdict(dict)
for row in my_df.groupby(['Col1','Col2']).size().iteritems():
resul[row[0][0]][row[0][1]] = row[1]
pprint.pprint(resul)
按预期给出:
defaultdict(<class 'dict'>,
{'A': {'a': 1, 'b': 2, 'e': 1},
'B': {'c': 2, 'e': 1},
'C': {'a': 1}})
如果你想摆脱 defaultdict 而想要一个普通的 dict:
resul = dict(resul)
推荐阅读
- c - ftell() 函数给出错误答案
- r - 如果 R data.table 中只有一个唯一值,则检查唯一值并返回它的最快方法
- node.js - 为什么“请求”类型上不存在发生的属性“用户”
' - asp.net-core - .NET Core API 使用 ImageSharp、MemoryStream 和 FileStream 异步保存图像上传
- android - 类内合成绑定的空对象引用错误
- database - Flutter:在应用级别按类别过滤产品?
- html - 在 css 中布置表格
- java - Java volatile 自定义对象 - 完整/深度对象可见性
- javascript - ajax调用后如何初始化Datatable
- python-3.x - 计算 AWS Comprehend Sentiment 成本