【问题标题】:How to count a value in a specific row of an array with Python [duplicate]如何使用Python计算数组特定行中的值[重复]
【发布时间】:2019-08-20 11:21:44
【问题描述】:

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

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

【问题讨论】:

    标签: python arrays numpy artificial-intelligence


    【解决方案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,:])
    

    【讨论】:

      【解决方案2】:

      您可以简单地将 14.row 的值相加,然后得到病狗的数量(计数):

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

      【讨论】:

        猜你喜欢
        • 2018-04-29
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2022-08-23
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        相关资源
        最近更新 更多