1

How to implement the Excel 'COUNTIF()' using python

Please see the below image for the reference, I have a column named 'Title' and it contains some text (CD,PDF). And I need to find the count of the string in the column as given below.

No.of CD : 4
No.of PDF: 1

By using Excel I could find the same by using the below formula

=COUNTIF($A$5:$A$9,"CD")

How can I do the same using python.

enter image description here

Vineesh TP
  • 7,755
  • 12
  • 66
  • 130
  • Might [this](https://stackoverflow.com/questions/2643850/what-is-a-good-way-to-do-countif-in-python) help? – JvdV Sep 18 '19 at 09:28
  • Hi, please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly – anky Sep 18 '19 at 09:32
  • df[df['A'] == 'CD'].sum() – min2bro Sep 18 '19 at 09:36

2 Answers2

2

For a simple summary of list item counts, try .value_counts() on a Pandas data frame column:

my_list = ['CD','CD','CD','PDF','CD']        
df['my_column'] = pd.DataFrame(my_list)    # create data frame column from list
    
df['my_column'].value_counts()

enter image description here

... or on a Pandas series:

pd.Series(my_list).value_counts()

enter image description here

Having a column of counts can be especially useful for scrutinizing issues in larger datasets. Use the .count() method to create a column with corresponding counts (similar to using COUNTIF() to populate a column in Excel):

enter image description here

df['countif'] = [my_list.count(i) for i in my_list]  # count list item occurrences and assign to new column

display(df[['my_column','countif']])  # view results

enter image description here

fact_finder
  • 142
  • 2
  • 11
1

I guess you can do map to compare with "CD" then sum all the values Example: Create "title" data:

df = pd.DataFrame({"Title":["CD","CD","CD","PDF","CD"]})

The countif using map then sum

df["Title"].map(lambda x: int(x=="CD")).sum()
Jose Vu
  • 621
  • 5
  • 13