2016-12-09 102 views
2

我需要找到一種方法來計算從0到9出現在一個隨機矩陣中的每一數目多少次使用np.random.randint()多少次的號碼出現在一個numpy的陣列

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

創建例如,如果長度的矩陣= 4

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

多少次數4出現?它應該返回5.

+0

首先,弄清楚你是怎麼做的。 –

回答

0

你可以扁平化矩陣,然後使用列表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) 
+2

[Counting a list](http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)比這更簡單:' flat.count(x)'就足夠了。 – TemporalWolf

+2

另外,numpy有一個[flatten](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html): 'list(m.flatten())。count (x)' – TemporalWolf

+0

我很好奇哪種方法更快,因爲你仍然需要將它轉換爲列表@TemporalWolf – rofls

2

可以使用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,然後由於python評估True爲1,你可以總結數組項目以獲得預期項目的數量。

4

你應該能夠得到這個倒也乾脆:

list(m.flatten()).count(x) 

另一種選擇是可能更快,是使用內置count_nonzero()的numpy的:

np.count_nonzero(m == x) 

萬歲內置函數。

+0

謝謝!我想我會用這個 – Teddy

0

如果你想從所有矩陣元素的頻率,這是一個使用numpy.ndarray.flattencollections.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})