Vineesh TP
Vineesh TP

Reputation: 7943

Excel 'COUNTIF() ' functionality using Python Pandas

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

Upvotes: 1

Views: 1774

Answers (2)

fact_finder
fact_finder

Reputation: 192

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

Upvotes: 2

Jose Vu
Jose Vu

Reputation: 696

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()

Upvotes: 1

Related Questions