在 pandas 数据帧上使用isull()和groupby() [英] Using isnull() and groupby() on a pandas dataframe

查看:22
本文介绍了在 pandas 数据帧上使用isull()和groupby()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含列‘A’、‘B’、‘C’的DataFrame DF。 我想计算‘B’列中按‘A’分组的NULL值的数量,并根据它创建一个词典:

尝试以下操作失败: df.groupby('A')['B'].isnull().sum().to_dict()

如有任何帮助,将不胜感激。

推荐答案

安装

df = pd.DataFrame(dict(A=[1, 2] * 3, B=[1, 2, None, 4, None, None]))

df

   A    B
0  1  1.0
1  2  2.0
2  1  NaN
3  2  4.0
4  1  NaN
5  2  NaN

选项1

df['B'].isnull().groupby(df['A']).sum().to_dict()

{1: 2.0, 2: 1.0}

选项2

df.groupby('A')['B'].apply(lambda x: x.isnull().sum()).to_dict()

{1: 2, 2: 1}

选项3
发挥创造力

df.A[df.B.isnull()].value_counts().to_dict()

{1: 2, 2: 1}

选项4

from collections import Counter

dict(Counter(df.A[df.B.isnull()]))

{1: 2, 2: 1}

选项5

from collections import defaultdict

d = defaultdict(int)
for t in df.itertuples():
    d[t.A] += pd.isnull(t.B)
dict(d)

{1: 2, 2: 1}

选项6
不必要的复杂

(lambda t: dict(zip(t[1], np.bincount(t[0]))))(df.A[df.B.isnull()].factorize())

{1: 2, 2: 1}

选项7

df.groupby([df.B.isnull(), 'A']).size().loc[True].to_dict()

{1: 2, 2: 1}

这篇关于在 pandas 数据帧上使用isull()和groupby()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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