Allen Allen - 2 years ago 175
Python Question

Python - Get percentage of minority class in a list

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

Answer Source

Use collections.Counter,

import collections

list1 = [1,1,1,-1,-1]
p = min(collections.Counter(list1).values())*1.0/len(list1)
# Output

collections.Counter(list1) returns a dict with the key:value pair element:frequency. In this case, it will be Counter({1: 3, -1: 2}).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download