微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

怎么用Pandas DataFrame统计每一行0值的个数?

这里有两种方法

  1. 首先可以通过(df == 0).astype(int).sum(axis=1),举个例子:

    in[34]:df = pd.DataFrame({'a':[1,0,0,1,3],'b':[0,0,1,0,1],'c':[0,0,0,0,0]})
    in[35]:df
    Out[35]: 
    a  b  c
    0  1  0  0
    1  0  0  0
    2  0  1  0
    3  1  0  0
    4  3  1  0
    
    
    
    in[36]:(df == 0).astype(int).sum(axis=1)
    
    Out[36]: 
    
    0    2
    1    3
    2    2
    3    2
    4    1
    dtype: int64
    

拆开来看如下:

in[37]: df == 0
Out[37]:
a b c
0 False True True
1 True True True
2 True False True
3 False True True

4 False False True

in[38]:(df == 0).astype(int)
Out[38]:
a b c
0 0 1 1
1 1 1 1
2 1 0 1
3 0 1 1

4 0 0 1

或者更加省略一些是:(df == 0).sum(axis=1)

命令中转化成int不是特别必要,因为boolean类型在进行sum操作时会自动变为int类型。

  1. 另一种方法是通过使用apply()和value_counts():

in[40]: df.apply(lambda x : x.value_counts().get(0,0),axis=1)

Out[40]:
0 2
1 3
2 2
3 2
4 1
dtype: int64

原文:https://blog.csdn.net/kkkkkiko/article/details/80845859

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐