英文:
Count number of 1's in an array in Python
问题
我有一个名为```A```的数组。我想统计数组中的1的数量,但是我遇到了一个错误。下面是期望的输出。
```python
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_nonzero(A==1)
print(B)
错误信息是
in __getattr__
raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'count_nonzero'
期望的输出是
7
<details>
<summary>英文:</summary>
I have an array ```A```. I want to count the number of 1's in the array but I am getting an error. I present the expected output.
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)
The error is
in getattr
raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'count'
The expected output is
7
</details>
# 答案1
**得分**: -1
The `np.count` function does not exist, you can use `np.count_nonzero` instead.
```py
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_nonzero(A==1) # or just A, if you'll never have anything other than 0 or 1
print(B)
英文:
The np.count
function does not exist, you can use np.count_nonzero
instead.
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_nonzero(A==1) # or just A, if you'll never have anything other than 0 or 1
print(B)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论