Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the count of positive and negative values from an array

Tags:

python

list

count

I need to work with an array to make some computations. I have the following data:

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

and I would need to play with the data and extract from each column the number of positive and negative values so the output should be like:

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

I gave it a try using a for loop with no success and with Numpy as well, but I do not really know how to use it.

What is the best way to get that result?

like image 759
Ben2pop Avatar asked Dec 28 '17 09:12

Ben2pop


People also ask

How do you count the number of positive numbers in an array in Python?

Example #1: Count positive and negative numbers from given list using for loop Iterate each element in the list using for loop and check if num >= 0, the condition to check positive numbers. If the condition satisfies, then increase pos_count else increase neg_count.

How do you count positive and negative numbers in SQL?

To count number of positive and negative votes, you can use CASE statement along with aggregate function SUM().


1 Answers

Probably the most elegant way is to convert it to a numpy array first, then perform a condition >= 0 on it, and then calculate the sum(..) over the first axis:

import numpy as np

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

This then yields:

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

So by using np.array(x) >= 0, we obtain a 2d-array of booleans:

>>> 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)

Since True counts as one, and False as zero, by calculing the sum per column, we thus count the number of positive numbers.

In case you want to count strictly positive numbers (so only larger than zero), you should omit the = in >=:

>>> np.sum(np.array(x) > 0, axis=0)
array([3, 3, 3, 3, 3, 0])
like image 122
Willem Van Onsem Avatar answered Sep 30 '22 16:09

Willem Van Onsem