dataframe记录数_通过Pandas DataFrame计数每行零个数?

Given a DataFrame I would like to compute number of zeros per each row. How can I compute it with Pandas?

This is presently what I ve done, this returns indices of zeros

def is_blank(x):

return x == 0

indexer = train_df.applymap(is_blank)

解决方案

Use a boolean comparison which will produce a boolean df, we can then cast this to int, True becomes 1, False becomes 0 and then call count and pass param axis=1 to count row-wise:

In [56]:

df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,0,1,0,1], 'c':[0,0,0,0,0]})

df

Out[56]:

a b c

0 1 0 0

1 0 0 0

2 0 1 0

3 1 0 0

4 3 1 0

In [64]:

(df == 0).astype(int).sum(axis=1)

Out[64]:

0 2

1 3

2 2

3 2

4 1

dtype: int64

Breaking the above down:

In [65]:

(df == 0)

Out[65]:

a b c

0 False True True

1 True True True

2 True False True

3 False True True

4 False False True

In [66]:

(df == 0).astype(int)

Out[66]:

a b c

0 0 1 1

1 1 1 1

2 1 0 1

3 0 1 1

4 0 0 1

EDIT

as pointed out by david the astype to int is unnecessary as the Boolean types will be upcasted to int when calling sum so this simplifies to:

(df == 0).sum(axis=1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值