[英]How many times a number appears in a numpy array
我需要找到一種方法來計算使用np.random.randint()
創建的隨機矩陣中從 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)
例如,如果矩陣長度 = 4
數字 4 出現了多少次? 它應該返回 5。
你應該能夠很簡單地得到這個:
list(m.flatten()).count(x)
另一個可能更快的選項是使用 numpy 內置count_nonzero()
:
np.count_nonzero(m == x)
萬歲內置函數。
您可以使用sum
函數:
In [52]: m = np.random.randint(0,9,(4,4))
In [53]: m
Out[53]:
array([[8, 8, 2, 1],
[2, 7, 1, 2],
[8, 6, 8, 7],
[5, 2, 5, 2]])
In [56]: np.sum(m == 8)
Out[56]: 4
m == 8
將為每個 8 返回一個包含 True 的布爾數組,然后由於 python 將 True 評估為 1,您可以對數組項求和以獲得預期項的數量。
如果你想從所有矩陣元素中獲取頻率,這里有一個使用numpy.ndarray.flatten和collections.Counter的簡單解決方案:
import numpy as np
import collections
p = int(input("Length of matrix: "))
m = np.random.randint(0, 9, (p, p))
print(m)
print(collections.Counter(m.flatten()))
例如,當 p=3 時,您會得到如下結果:
[[8 4 8]
[5 1 1]
[1 1 1]]
Counter({1: 5, 8: 2, 4: 1, 5: 1})
您可以展平矩陣,然后使用 list 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)
我會嘗試使用參數 return_counts=True 的 numpy unique 函數(參見: https ://numpy.org/doc/stable/reference/generated/numpy.unique.html)。
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
# print(m)
un, nm = np.unique(m, return_counts = True)
# if number that you are looking for is 1 then:
print(nm[un==1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.