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

本文介绍了两种在Python的pandas库中计算DataFrame每一行中0出现次数的方法。第一种方法是使用(df==0).astype(int).sum(axis=1)或更简洁的(df==0).sum(axis=1),第二种方法是利用apply()结合value_counts()函数。这些方法适用于需要统计特定值出现频率的数据预处理场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里有两种方法:

  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值