I need to find a way to count how many times each number from 0 to 9 appears in a random matrix created using np.random.randint()
import numpy as np
p = int(input("Length of matrix: "))
m = np.random.randint(0,9,(p,p))
print(m)
For example if length of matrix = 4
How many times does the number 4 appear? It should return 5.
You should be able to get this pretty simply:
list(m.flatten()).count(x)
Another option which is probably faster, is to use the numpy builtin count_nonzero()
:
np.count_nonzero(m == x)
Hooray builtin functions.
You can use sum
function:
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
will return a boolean array contains True for each 8 then since python evaluates the True as 1 you can sum up the array items in order to get the number of intended items.
If you want to get the frequency from all matrix elements, here's a simple solution using numpy.ndarray.flatten and 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()))
For example, when p=3 you'd get something like this:
[[8 4 8]
[5 1 1]
[1 1 1]]
Counter({1: 5, 8: 2, 4: 1, 5: 1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With