在Python中计算数组中的1的数量

huangapple go评论90阅读模式
英文:

Count number of 1's in an array in Python

问题

  1. 我有一个名为```A```的数组我想统计数组中的1的数量但是我遇到了一个错误下面是期望的输出
  2. ```python
  3. import numpy as np
  4. 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,
  5. 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
  6. B = np.count_nonzero(A==1)
  7. print(B)

错误信息是

  1. in __getattr__
  2. raise AttributeError("module {!r} has no attribute "
  3. AttributeError: module 'numpy' has no attribute 'count_nonzero'

期望的输出是

  1. 7
  1. <details>
  2. <summary>英文:</summary>
  3. I have an array ```A```. I want to count the number of 1&#39;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)

  1. The error is

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

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

  1. The expected output is

7

  1. </details>
  2. # 答案1
  3. **得分**: -1
  4. The `np.count` function does not exist, you can use `np.count_nonzero` instead.
  5. ```py
  6. import numpy as np
  7. 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,
  8. 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
  9. B=np.count_nonzero(A==1) # or just A, if you'll never have anything other than 0 or 1
  10. print(B)
英文:

The np.count function does not exist, you can use np.count_nonzero instead.

  1. import numpy as np
  2. 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,
  3. 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
  4. B=np.count_nonzero(A==1) # or just A, if you&#39;ll never have anything other than 0 or 1
  5. print(B)

huangapple
  • 本文由 发表于 2023年2月6日 15:40:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定