I have a pandas dataframe with a column reporting a certain number of cities.
I need to count the frequency of each city occurrence and put that in a collections.Counter
object.
The dataframe is like this:
col1 New York Tokyo Tokyo Beijing ...
My collections.Counter
objects should then look something like this:
({'New York': 1, 'Tokyo': 2, 'Beijing': 1,...})
. Is there a way to do this?
(I stress that the output has to be a collections.Counter
object.)
Answer
As Chris commented, you can use use Counter(df.col1)
:
>>> import pandas as pd >>> df = pd.DataFrame({ 'col1': ['New York', 'Tokyo', 'Tokyo', 'Beijing'] }) >>> from collections import Counter >>> Counter(df.col1) Counter({'New York': 1, 'Tokyo': 2, 'Beijing': 1})