栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Pandas在groupby函数中计算空值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pandas在groupby函数中计算空值

我认为你需要

groupby
使用
sum
NaN
值:

df2 = df.C.isnull().groupby([df['A'],df['B']]).sum().astype(int).reset_index(name='count')print (df2)     A      B  count0  bar    one      01  bar  three      02  bar    two      13  foo    one      24  foo  three      15  foo    two      2

如果需要过滤器,首先添加

boolean indexing

df = df[df['A'] == 'foo']df2 = df.C.isnull().groupby([df['A'],df['B']]).sum().astype(int)print (df2)A    B    foo  one      2     three    1     two      2

或更简单:

df = df[df['A'] == 'foo']df2 = df['B'].value_counts()print (df2)one      2two      2three    1Name: B, dtype: int64

编辑:解决方案非常相似,只添加

transform

df['D'] = df.C.isnull().groupby([df['A'],df['B']]).transform('sum').astype(int)print (df)     A      B     C  D0  foo    one   NaN  21  bar    one  bla2  02  foo    two   NaN  23  bar  three  bla3  04  foo    two   NaN  25  bar    two   NaN  16  foo    one   NaN  27  foo  three   NaN  1

类似的解决方案:

df['D'] = df.C.isnull()df['D'] = df.groupby(['A','B'])['D'].transform('sum').astype(int)print (df)     A      B     C  D0  foo    one   NaN  21  bar    one  bla2  02  foo    two   NaN  23  bar  three  bla3  04  foo    two   NaN  25  bar    two   NaN  16  foo    one   NaN  27  foo  three   NaN  1


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639671.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号