Search code examples
pythoncounter

Percentage difference between two counter objects


I have two counter object like this:

A1 = {‘word1’: 7, ‘word2’: 5, ‘word3’: 4}
A2 = {‘word1’: 3, ‘word2’: 2, ‘word3’: 4}

I want to compute a percentage difference between the two counters, to obtain something like:

R = {‘word1’: -57.1, ‘word2’: -60, ‘word3’: 0}

I've tried this solution, but it gives me error

R = ((A2 - A1) / A1) * 100 

TypeError: unsupported operand type(s) for /: 'Counter' and 'Counter'

Any advice will be appreciated!


Solution

  • One approach is to use a dictionary comprehension:

    from collections import Counter
    
    A1 = Counter({'word1': 7, 'word2': 5, 'word3': 4})
    A2 = Counter({'word1': 3, 'word2': 2, 'word3': 4})
    
    res = {key: (A2.get(key, 0) / value - 1) * 100 for key, value in A1.items()}
    print(res)
    

    Output

    {'word1': -57.14285714285714, 'word2': -60.0, 'word3': 0.0}
    

    Another approach is to use the same comprehension but only give the results that are in the intersection of the Counter objects:

    # A1 with an extra key
    A1 = Counter({'word1': 7, 'word2': 5, 'word3': 4, 'word4': 5})
    A2 = Counter({'word1': 3, 'word2': 2, 'word3': 4})
    
    res = {key: (A2[key] / value - 1) * 100 for key, value in A1.items() if key in A2}
    print(res)
    

    Output

    {'word1': -57.14285714285714, 'word2': -60.0, 'word3': 0.0}
    

    Note that A2 - A1, will indeed subtract the counts, but only keeps results with positive values.