Python: How to multiply values of a Counter object?

Question:

I’m looking for a way to multiply the values of a Counter object, i.e.

a =  collections.Counter(one=1, two=2, three=3)
>>> Counter({'three': 3, 'two': 2, 'one': 1})

b = a*2
>>> Counter({'three': 6, 'two': 4, 'one': 2})

What’s the standard way of doing this in python?

Why I want to do this:
I have a sparse feature vector (bag of words represented by a Counter object) that I would like to normalize.

Asked By: John Smith

||

Answers:

You can add the Counter:

b = a+a
>>> print b
Counter({'three': 6, 'two': 4, 'one': 2})
Answered By: sshashank124

You can do this :

for k in a.keys():
     a[k] = a[k] * 2
Answered By: DavidK

This is an old question, but I just had the same issue during chemical formulae parsing. I extended the Counter class to accept multiplication with integers. For my case, the following is sufficient – it may be extended on demand:

class MCounter(Counter):
    """This is a slight extention of the ``Collections.Counter`` class
    to also allow multiplication with integers."""

    def __mul__(self, other):
        if not isinstance(other, int):
            raise TypeError("Non-int factor")
        return MCounter({k: other * v for k, v in self.items()})

    def __rmul__(self, other):
        return self * other  # call __mul__

    def __add__(self, other):
        return MCounter(super().__add__(other))

So with above, you can multiply from left and right with integers as well. I needed to redefine __add__such that the type MCounter was preserved. If one needs to use subtraction, & and |, that needs to be implemented likewise.

Answered By: Dr. V
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.