【问题标题】:Extract the count of positive and negative values from an array从数组中提取正负值的计数
【发布时间】:2017-12-28 09:47:35
【问题描述】:

我需要使用数组来进行一些计算。我有以下数据:

x = [[81, 68, 71, 71, 67, -72], [79, 77, 88, 88, 59, -71], [67, 71, 68, 68, 85, -66]]

我需要处理数据并从每列中提取正负值的数量,因此输出应该是这样的:

positive_value = [3,3,3,3,0]
negative_vaue = [0,0,0,0,3]

我尝试使用 for 循环但没有成功,也使用 Numpy,但我真的不知道如何使用它。

获得该结果的最佳方法是什么?

【问题讨论】:

  • 为什么 positive_value = [3,3,3,3,0] ?
  • @keyvanvafaee:我认为 OP 希望明智地计算行数。所以第一列有三个正值,第二列也有三个,等等。
  • 0你想怎么算?
  • “我尝试了使用 for 循环,但没有成功” 你应该向我们展示你尝试了什么。您可能投了反对票,因为您的问题不包含您自己解决此问题的尝试。
  • 转换成数组,转置。现在你的列已经变成了行,你可以简单地计算其中有多少是正数,其余的变成负数

标签: python list count


【解决方案1】:

可能最优雅的方法是先将其转换为数组,然后对其执行条件>= 0,然后在第一个轴上计算sum(..)

import numpy as np

np.sum(np.array(x) >= 0, axis=0)

然后产生:

>>> np.sum(np.array(x) >= 0, axis=0)
array([3, 3, 3, 3, 3, 0])

所以通过使用np.array(x) >= 0,我们获得了一个二维布尔数组:

>>> np.array(X) >= 0
array([[ True,  True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True, False]], dtype=bool)

由于 True 计为 1,False 计为 0,因此通过计算每列的总和,我们计算正数的数量。

如果你想严格计算正数(所以只大于零),你应该省略>=中的=

>>> np.sum(np.array(x) > 0, axis=0)
array([3, 3, 3, 3, 3, 0])

【讨论】:

    【解决方案2】:

    没有任何库

    pos = [ sum(y>=0 for y in x)  for x in zip(*mylist) ]
    neg = [ len(mylist)-x for x in pos]
    print(pos, neg)
    

    demo

    【讨论】:

    • 我可能会在列表 comp 之外做len(mylist); OTOH,len 非常快,所以除非mylist 很大,否则它只会对速度产生微小的影响。
    • @PM2Ring 在实际代码中,我也是。让我们留下一些功课:)
    【解决方案3】:

    你可以使用 count_nonzero 函数,为此你可能需要修改你的数组

    >>> np.count_nonzero(np.eye(4))  #identity matrix              
    4            
    >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])   
    5           
    >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=0)         
    array([1, 1, 1, 1, 1])         
    >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)        
    array([2, 3])
    

    【讨论】:

      【解决方案4】:
      >>> x = [[81, 68, 71, 71, 67, -72], [79, 77, 88, 88, 59, -71], [67, 71, 68, 68, 85, -66]]
      >>> zipped = list(zip(*x))
      >>> for items in zipped:
          pos = len(list(filter(lambda i: i > 0, items)))
          neg = len(list(filter(lambda i: i < 0, items)))
          positive_values.append(pos)
          negative_values.append(neg)
      
      
      >>> positive_values
      [3, 3, 3, 3, 3, 0]
      >>> negative_values
      [0, 0, 0, 0, 0, 3]
      

      【讨论】:

      • 这看起来不像 OP 的目标输出。
      • 是的,这不是我要找的……我这样做是为了计算加权平均值……
      • @Ben2pop 你还没有告诉我们你想对数据中的零项做什么。
      【解决方案5】:
      twoD = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
      pos = neg = 0
      for row in twoD:
         for col in row:
            if col < 0:
               neg += 1
            else:
               pos += 1
      print('Number of positive integers are', pos, 'Number of negative integers are', neg)
      

      【讨论】:

        【解决方案6】:

        上面splash58的答案中的代码有效,而且写得很漂亮:

        matrix_2d = [[81, 68, 71, 71, 67, 72], [79, 77, 88, 88, 59, -71], [67, 71, 68, 68, 85, -66]]
        
        pos = [sum(y >= 0 for y in x)  for x in zip(*matrix_2d)]
        neg = [len(matrix_2d) - x for x in pos]
        
        print('Positive counts by columns: ', pos)
        print('Nagetive counts by columns: ', neg)
        

        但是,如果您想更深入地了解算法的工作原理,这里有一个更简单的版本,虽然更长更冗长:

        matrix_2d = [[81, 68, 71, 71, 67, 72], [79, 77, 88, 88, 59, -71], [67, 71, 68, 68, 85, -66]]
        
        matrix_rows = len(matrix_2d)
        matrix_cols = len(matrix_2d[0])
        
        positive_counts = [0] * matrix_cols
        negative_counts = [0] * matrix_cols
        
        for col_idx in range(matrix_cols):
          for row_idx in range(matrix_rows):
            if matrix_2d[row_idx][col_idx] < 0:
              negative_counts[col_idx] += 1
            else:
              positive_counts[col_idx] += 1
        
        
        print('Positive counts by columns: ', positive_counts)
        print('Nagetive counts by columns: ', negative_counts)
        

        我改变了ma​​trix_2d[0, 5]的输入,所以预期的结果是:

        Positive counts by columns:  [3, 3, 3, 3, 3, 1]
        Nagetive counts by columns:  [0, 0, 0, 0, 0, 2]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-11
          • 2023-04-03
          相关资源
          最近更新 更多