np里一个数出现的次数python代码
时间: 2024-02-05 13:04:17 浏览: 89
要统计NumPy数组中某个数出现的次数,可以使用以下两种方法:
方法一:使用NumPy的函数bincount()
```python
import numpy as np
arr = np.array(\[0, 0, 1, 1, 1, 3, 4, 5, 6, 5, 4, 3, 4, 2, 23\])
x = 1
count = np.bincount(arr)
x_count = count\[x\]
print(x_count)
```
结果:3
方法二:使用Python的循环
```python
import numpy as np
arr = np.array(\[0, 0, 1, 1, 1, 3, 4, 5, 6, 5, 4, 3, 4, 2, 23\])
x = 1
count = 0
for num in arr:
if num == x:
count += 1
print(count)
```
结果:3
以上两种方法都可以用来统计NumPy数组中某个数出现的次数。
#### 引用[.reference_title]
- *1* [Python & Numpy: 统计列表或数组中元素/数值的出现次数](https://blog.csdn.net/suoluo_2020/article/details/124544859)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [python统计数组中所有元素出现的次数](https://blog.csdn.net/oMoDao1/article/details/85004889)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Python统计一个列表中每个元素出现的次数](https://blog.csdn.net/ZhiAi_ZhengLiLi/article/details/99083398)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文