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?
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.
To count number of positive and negative votes, you can use CASE statement along with aggregate function SUM().
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With