Reputation: 3659
I have a panda series that looks like this;
0 -10.93
1 -9.18
2 -6.87
3 7.90
4 9.18
5 6.87
6 9.12
7 9.12
8 8.75
9 7.75
I would like to get the percentage of positive numbers in this series. In this case, the answer should be 70%.
I am using python 3.6
Upvotes: 1
Views: 1217
Reputation: 862911
Use mean
of boolean mask:
a = s.gt(0).mean() * 100
a = (np.sign(s) == 1).mean() * 100
print (a)
70.0
If want also all negative, positive and zero values is possible use numpy.sign
with value_counts
:
print (s)
0 -10.93
1 -9.18
2 -6.87
3 7.90
4 9.18
5 6.87
6 9.12
7 9.12
8 8.75
9 0.00 <- changed last value to 0
Name: a, dtype: float64
b = np.sign(s).value_counts(normalize=True).rename({0:'zero', 1:'pos', -1:'neg'})
print (b)
pos 0.6
neg 0.3
zero 0.1
Name: a, dtype: float64
Upvotes: 2
Reputation: 76927
Use
In [381]: s.ge(0).sum() / len(s.index) * 100.
Out[381]: 70.0
Or
In [383]: 100. * (s >= 0).sum() / len(s.index)
Out[383]: 70.0
Upvotes: 1