一个数字出现在numpy数组中的次数

Ted*_*ddy 4 python numpy count python-3.x

我需要找到一种方法来计算从0到9的每个数字出现在使用的随机矩阵中的次数 np.random.randint()

import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
Run Code Online (Sandbox Code Playgroud)

例如,如果矩阵的长度= 4

  • [[3 4 6 5] [3 4 4 3] [4 2 4 8] [6 8 2 7]]

4号出现多少次?它应该返回5.

Tem*_*olf 8

你应该能够很简单地得到它:

list(m.flatten()).count(x)
Run Code Online (Sandbox Code Playgroud)

另一个可能更快的选择是使用numpy内置count_nonzero():

np.count_nonzero(m == x)
Run Code Online (Sandbox Code Playgroud)

万岁内置功能.


rof*_*fls 1

您可以展平矩阵,然后使用列表count()方法:

from collections import Counter
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
flat = [item for sublist in m for item in sublist]
flat.count(4)
Run Code Online (Sandbox Code Playgroud)

  • [计算列表](http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)甚至比这更容易:`flat .count(x)` 就足够了。 (2认同)
  • 另外,numpy 有一个 [flatten](https://docs.scipy.org/doc/numpy/reference/ generated/numpy.ndarray.flatten.html): `list(m.flatten()).count(x) ` (2认同)