【问题标题】:Comparing Boolean Arrays: Count number of times BOTH are True比较布尔数组:计算两者都为真的次数
【发布时间】:2018-03-24 19:11:25
【问题描述】:

我想知道如何计算多个 NumPy bool 数组中真实元素的数量。例如,在哪些试验上 A 和 B == 1。以下是我尝试过的。

A = array([1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 2, 2, 1])
B = np.array([ 1.,  1.,  1.,  1.,  1.,  1.,  0.,  1.,  0.,  1.,  1.,  1.,  1., 0.,  1.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  1.,  0.,  1.,  1., 1.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,  0.,  0., 0.,  1.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  1.,  1.,  1.,  1., 1.,  1.,  1.,  0.,  1.,  0.,  1.,  0.,  1.,  1.,  1.,  1.,  0., 0.,  1.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  1.,  0.,  1.,  1., 0.,  1.,  1.,  1.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0., 1.,  0.,  1.,  0.,  1.,  1.,  1.,  0.,  0.,  1.,  1.,  1.,  0., 0.,  1.,  1.,  0.,  1.,  1.,  1.,  0.,  1.,  0.,  1.,  1.,  0., 1.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,  1.,  0., 1.,  1.,  1.,  1.,  1.,  0.,  0.,  1.,  0.,  1.,  0.,  1.,  1., 1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  1.,  1.,  1.,  1.,  0., 1.,  1.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  1.,  1.,  0.,  0., 0.,  0.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,  1., 0.,  0.,  1.,  0.,  1.,  1.,  1.,  0.])

num_trials = len(A)
slide_avg = np.zeros(num_trials)

for i in range(num_trials):
    if i < num_trials_slide:
        slide_avg[i] = np.sum(A[0:i+1] == 1 and B[0:i+1] == 1)/float(np.sum(A[0:i+1] == 1))

我收到以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

  • &amp;替换and
  • 认为应该是:np.sum(( A[0:i+1] == 1) &amp; (B[0:i+1] == 1))/float(np.sum(A[0:i+1] == 1)).
  • 然后我收到以下错误:TypeError: ufunc 'bitwise_and' not supported for the input types, and the input could not be safe to becovered to any supported types based on the cast rule ''safe''

标签: python numpy boolean ambiguous valueerror


【解决方案1】:

@AustinA 有一个非常聪明的answer,它利用了 1*1=1 这一事实。

一个可能的不足是在您有非整数值的情况下,即 2.0 和 0.5,在此逻辑下将计算为 1.0。如果是这种情况,另一种选择是:

np.sum((A == 1) & (B == 1))
# 24

但如果您使用所有整数,@Austin 的答案应该快 2 倍左右。

【讨论】:

    【解决方案2】:

    如果您只是将数组按元素相乘成一个新数组(例如 C),则等于 1 的元素数将等于 A 和 B 都为真的元素数.

    len(np.where(A*B == 1)[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-01
      • 2014-03-01
      • 2016-05-05
      • 2016-03-11
      • 2011-10-02
      • 2022-01-23
      • 1970-01-01
      • 2012-07-28
      相关资源
      最近更新 更多