我有一個2d數組數據。並且每當第j次迭代爲1時想獲得一個計數。 其中i =行,j =列。 如何在沒有for循環的情況下執行此操作?獲得一個2d數組列的數據
概念是這樣的:
for r in range(row):
if(data[r][j] == 1)
amount += 1
我有一個2d數組數據。並且每當第j次迭代爲1時想獲得一個計數。 其中i =行,j =列。 如何在沒有for循環的情況下執行此操作?獲得一個2d數組列的數據
概念是這樣的:
for r in range(row):
if(data[r][j] == 1)
amount += 1
你可以做如下:
import numpy as np
a = np.array([[0, 1], [1, 1]])
j = 1
np.sum(a[:, j] == 1)
會給你2作爲結果 ,而np.sum(a[:, 0] == 1)
會給1
如果作爲mentio您的評論定義你想使用多個陣列的條件,你可以使用np.logical_and(condition1, condition2)
:
np.sum(np.logical_and(a[:, 0] == 1, b[:, 0] == 2))
我interprete這個問題,這樣要迭代兩者的行和列,並添加1至amount
因爲這是在數據中的每個條目1.這可能是如下完成循環。
import numpy as np
data = np.ones((6,8))
amount = data[data == 1].sum()
print amount
如果instaead,您修復一列j
,只希望在此列的金額:
import numpy as np
j=7
data = np.ones((6,8))
amount = data[:,j][data[:,j]==1].sum()
print amount
我想通過一個具體的j列的每一行進行迭代。 – user
是否可以包含第二個條件? 例如:np.sum(arrayB = 2和a [:,0] == 1) – user
@user您可以使用np.logical_and(a [:, 0] == 1,b [:, 0] == 2) –