[英]Extract the count of positive and negative values from an array
我需要使用一个数组来进行一些计算。 我有以下数据:
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 都没有成功,但我真的不知道如何使用它。
获得该结果的最佳方法是什么?
可能最优雅的方法是先将其转换为numpy数组,然后对其执行条件>= 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
数组:
>>> 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])
没有任何图书馆
pos = [ sum(y>=0 for y in x) for x in zip(*mylist) ]
neg = [ len(mylist)-x for x in pos]
print(pos, neg)
您可以使用 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])
>>> 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]
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)
上面来自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)
我改变了matrix_2d[0, 5]的输入,所以预期的结果是:
Positive counts by columns: [3, 3, 3, 3, 3, 1]
Nagetive counts by columns: [0, 0, 0, 0, 0, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.