You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas统计DataFrame每行非零值的列数?

如何给Pandas DataFrame新增列统计每行非零值数量?

可以通过Pandas的布尔判断+按行求和快速实现,下面是具体步骤:

1. 构造示例DataFrame

import pandas as pd

data = {
    'col1': [0, 0, 0, 0],
    'col2': [0, 0, 0, 2],
    'col3': [2, 0, 8, 2],
    'col4': [3, 3, 3, 3],
    'col5': [0, 0, 0, 0]
}
df = pd.DataFrame(data)

2. 新增统计非零值数量的列

有两种常用写法,效果完全一致:

方法一:用ne(0)判断非零后求和

df['nonzero'] = df.ne(0).sum(axis=1)

方法二:转为布尔类型后求和

df['nonzero'] = df.astype(bool).sum(axis=1)

3. 最终结果

执行后DataFrame会变成:

col1col2col3col4col5nonzero
002302
000301
008302
022303

原理说明

  • df.ne(0):生成一个布尔DataFrame,非零元素标记为True,零标记为False
  • astype(bool):将数值型数据转为布尔值,非零值对应True,零对应False
  • sum(axis=1):按行对布尔值求和(True等价于1,False等价于0),得到每行的非零值数量

内容的提问来源于stack exchange,提问作者Maths12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:20:08