如何使用Python计算数组的特定行中的值

时间:2019-03-29 13:41:28

标签: python arrays numpy artificial-intelligence

所以基本上我有一个数组,它由14行和426列组成,每一行代表一只狗的一个属性,每一列代表一只狗,现在我想知道有多少只狗生病了,这个属性由14.行。 0 =健康,1 =生病,那么如何计算特定行?

我尝试使用numpy.count_nonzero,但这会计算整个数组的值,有没有办法告诉它仅对特定行进行计数?

2 个答案:

答案 0 :(得分:2)

您可以简单地对14.row的值求和,得出患病狗的数量(计数):

count = A[13,:].sum() # number of ill dogs -- 13 because the index starts with 0

答案 1 :(得分:1)

假设我们有这个向量:

>import numpy as np
>arr = np.arange(30).reshape(6,5)
>arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29]])

这样,您将获得特定行的所有值的总和:

>np.sum(arr[1,:]) #On row 1
35

针对您的具体情况,使用:

>np.sum(arr[13,:])