在 pandas 组的字典中仅保留没有None值的键 [英] keep only keys without None values in dictionary from pandas groups

查看:74
本文介绍了在 pandas 组的字典中仅保留没有None值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> df = pd.DataFrame({'a': [1,1,1,2,2,3,3,3,3,4,4,5,5], 
'b': [0,1,1,0,1,0,0,1,4,1,0,3,0], 
'v': [2,4,3,7,6,5,9,3,2,4,5,2,3]})
>>> df
    a  b  v
0   1  0  2
1   1  1  4
2   1  1  3
3   2  0  7
4   2  1  6
5   3  0  5
6   3  0  9
7   3  1  3
8   3  4  2
9   4  1  4
10  4  0  5
11  5  3  2
12  5  0  3

>>> df.groupby(by =['a', 'b']).v.apply(list).unstack().to_dict('index')
{1: {0: [2], 1: [4, 3], 3: None, 4: None}, 2: {0: [7], 1: [6], 3: None, 4: 
None}, 3: {0: [5, 9], 1: [3], 3: None, 4: [2]}, 4: {0: [5], 1: [4], 3: None, 4: 
None}, 5: {0: [3], 1: None, 3: [2], 4: None}}

如何在输出字典中避免使用None值的键?在当前条件下,我的字典的大小比使用所需的键大了20倍.

How can the keys with None values be avoided in the output dictionary? In the present condition, my dictionary ends up 20x bigger than it should just with the needed keys.

推荐答案

使用相同的想法,只需两次to_dict

Using same idea , just need to_dict twice

df.groupby(by =['a', 'b']).v.apply(list).groupby(level=0).agg(lambda x : x.reset_index(level=0,drop=True).to_dict()).to_dict()
Out[1092]: 
{1: {0: [2], 1: [4, 3]},
 2: {0: [7], 1: [6]},
 3: {0: [5, 9], 1: [3], 4: [2]},
 4: {0: [5], 1: [4]},
 5: {0: [3], 3: [2]}}

这篇关于在 pandas 组的字典中仅保留没有None值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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