2

How to count number of values by their name? I have a pandas data frame:

word token 
physical I-Problem 
design I-Problem 
for I-Problem 
XML I-Problem 
databases I-Problem 
which o 
is o 
the o 
process o 

I need to count how many I-Problem in the token. I tried df['token'].count('I-Problem') but it doesn't work.

expected output :

I-Problem : 5

or

5
Chang
  • 77
  • 6
  • Could've used [str.count](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html) instead of just count `df['token'].str.count('I-Problem').sum()` though apparently numpy sum is fastest `(df['token'].values == 'I-Problem').sum()` things may have changed over time though [timings](https://stackoverflow.com/a/35277776/15497888) – Henry Ecker Sep 21 '21 at 02:09

1 Answers1

2

Use value_counts:

>>> df['token'].value_counts()['I-Problem']
5
>>> 

Or try tolist:

>>> df['token'].tolist().count('I-Problem')
5
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114