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

Python中统计numpy数组内1的数量报错求助

解决Numpy数组统计元素数量报错:AttributeError: module 'numpy' has no attribute 'count'

问题场景

现有Numpy数组A,需要统计其中数值1的出现次数,原代码使用np.count()导致报错,期望输出结果为7。

原错误代码:

import numpy as np

A=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0,
       0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

B=np.count(A==1)
print(B)

报错信息:

in __getattr__
    raise AttributeError("module {!r} has no attribute "

AttributeError: module 'numpy' has no attribute 'count'

错误原因

Numpy模块本身没有count()这个顶层函数,调用不存在的API导致了报错。

正确实现方法

以下几种方式都可以正确统计数组中1的数量:

方法1:使用np.sum()

布尔数组中True会被视为1,False视为0,直接求和即可得到1的数量:

import numpy as np

A=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0,
       0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

B = np.sum(A == 1)
print(B)  # 输出7

方法2:使用np.count_nonzero()

该函数专门用于统计数组中非零元素的数量,结合条件判断可精准统计1的个数:

B = np.count_nonzero(A == 1)
print(B)  # 输出7

如果数组中只有0和1两种值,也可以直接简化为np.count_nonzero(A)。

方法3:使用np.bincount()

适合整数数组,会统计每个整数出现的次数,通过索引获取目标数值的计数:

counts = np.bincount(A)
B = counts[1]  # 索引1对应数值1的出现次数
print(B)  # 输出7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:38:26