Reputation: 19947
Suppose I have a list, how can I write an elegant one-liner to calculate the percentage of the minority class in a list?
For example, for list1 = [1,1,1,-1,-1]
, the minority class is -1
. The percentage of -1
in the list will be 2/5=0.4
For another list list2 = [1,-1,-1,-1,-1]
, the minority class is 1
. The percentage of 1
in the list will be 1/5=0.2
Upvotes: 1
Views: 381
Reputation: 18017
Use collections.Counter
,
import collections
list1 = [1,1,1,-1,-1]
p = min(collections.Counter(list1).values())*1.0/len(list1)
print(p)
# Output
0.4
collections.Counter(list1)
returns a dict with the key:value pair element:frequency
. In this case, it will be Counter({1: 3, -1: 2})
.
Upvotes: 3
Reputation: 81614
You can use a Counter
:
from collections import Counter
nums = [1,-1,-1,-1,-1]
# if using Python 2 use float(len(nums))
print(Counter(nums).most_common()[-1][-1] / len(nums))
>> 0.2
Counter.most_common()
returns a list of tuples of the form (element, count)
ordered from most to least common, so most_common()[-1][-1]
returns the element that is the least common.
If there are several minorities, one of them will be chosen arbitrarily for the calculation. For example, using my code with nums = [3, 3, -1, 1, 2]
will also return 0.2
, using either -1
, 1
or 2
for the calculation.
Upvotes: 2