How to Perform a COUNTIF Function in Python?
Last Updated :
28 Nov, 2021
In this article, we will discuss how to perform a COUNTIF function in Python.
COUNTIF
We use this function to count the elements if the condition is satisfied. Notice that the word stands as COUNT + IF. That means we want to count the element if the condition that is provided is satisfied.
Approach
- We will have a DataFrame with some columns.
- We will use the function sum(). The sum() function will take an Iterable value. We will have a data frame with columns containing a list of elements. Then we will pass the condition to check whether the current element satisfies it or not.
- sum() returns an integer value. So we will store the value and print it.
Syntax
The syntax of the sum() function is as follows.
sum(data-list condition)
Let us take an example where we have a list called myList and in the list, there are integer values. We want the number of items greater than equals 40. So we can use the sum function as follows,
sum(mylist >= 40)
For using two conditions, we can either use AND( & ) or OR( | ) for separating the two conditions.
sum((myList) >= 40 & (myList <= 90)) # AND
sum((myList) >= 40 | (myList <= 90)) # OR
Method 1: Using a single column
First, let us create a DataFrame. Here we have two columns, which are views and likes. We will keep the length of each column the same.
Python3
# create a dictionary
my_data = {"views": [12, 13, 100, 80, 91],
"likes": [3, 8, 23, 17, 56]}
# convert to dataframe
my_df = pd.DataFrame(my_data)
Condition 1: If the views are more than 30
We will use the sum() function to check if, in the list of views column, the values are greater than 30. Then the sum function will count the rows that have corresponding views greater than 30.
Python3
import pandas as pd
# Data
my_data = {"views": [12, 13, 100, 80, 91],
"likes": [3, 8, 23, 17, 56]}
my_df = pd.DataFrame(my_data)
# Printing the DataFrame
print(my_df.to_string())
# Printing the number of views greater
# than 30
print("View greater than 30: ",
sum(my_df.views > 30))
Output

Condition 2: If the likes are more than 20
The sum() function to check if, in the list of likes column, the values are greater than 20. Then the sum function will count the rows that have corresponding likes greater than 20.
Python3
import pandas as pd
# Data
my_data = {"views": [12, 13, 100, 80, 91],
"likes": [3, 8, 23, 17, 56]}
my_df = pd.DataFrame(my_data)
# Printing the DataFrame
print(my_df.to_string())
# Printing the number of likes greater
# than 20
print("Likes greater than 20: ",
sum(my_df.likes > 20))
Output

Method 2: Using multiple columns
Condition 1: Likes are less than 20 AND view more than 30.
For satisfying two or more conditions, wrap each condition in brackets( ) and then use single & sign to separate them. Here we have only two conditions, so we need only one &.
Python3
import pandas as pd
# Data
my_data = {"views": [12, 13, 100, 80, 91], "likes": [3, 8, 23, 17, 56]}
my_df = pd.DataFrame(my_data) # DataFrame
# Printing the DataFrame
print(my_df.to_string())
# Calculating the number of views greater than 30
# as well as likes less than 20
sum = sum((my_df.likes < 20) & (my_df.views > 30))
print("Likes less than 20 and Views more than 30: ", sum)
Output

Condition 2: Using OR condition
We will use a single | sign to separate the conditions. | is used as either the first condition OR second OR third and so on.
Python3
import pandas as pd
# Data
my_data = {"views": [12, 13, 100, 80, 91], "likes": [3, 8, 23, 17, 56]}
my_df = pd.DataFrame(my_data) # DataFrame
# Printing the DataFrame
print(my_df.to_string())
# Calculating the number of views greater than 30
# or likes less than 20
sum = sum((my_df.likes < 20) | (my_df.views > 30))
print("Likes less than 20 or Views more than 30: ", sum)
Output
Similar Reads
How to Perform a COUNTIF Function in R? In this article, we will discuss how to perform COUNTIF function in R programming language. This is used to count the value present in the dataframe. We have to use sum() function to get the count. Syntax: sum(dataframe$column_name == value, na.rm=TRUE) where, dataframe is the input dataframecolumn_
2 min read
How to Perform an F-Test in Python In statistics, Many tests are used to compare the different samples or groups and draw conclusions about populations. These techniques are commonly known as Statistical Tests or hypothesis Tests. It focuses on analyzing the likelihood or probability of obtaining the observed data that they are rando
10 min read
How to Perform a SUMIF Function in Pandas? sumif() function is used to perform sum operation by a group of items in the dataframe, It can be applied on single and multiple columns and we can also use this function with groupby function. Method 1: SUMIF on all columns with groupby() This function is used to display sum of all columns with res
4 min read
How to Perform a Chi-Square Goodness of Fit Test in Python In this article, we are going to see how to Perform a Chi-Square Goodness of Fit Test in PythonThe Chi-Square Goodness of fit test is a non-parametric statistical hypothesis test that's used to determine how considerably the observed value of an event differs from the expected value. it helps us che
3 min read
How to use if, else & elif in Python Lambda Functions Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else & elif in Lambda Functions.Using if-else in lambda functionThe lamb
2 min read
Performing Excel like countifs in Python Pandas In this article, we are performing an excel-like countifs in Pandas. In Excel the data is in the form of a Table, So we can perform many arithmetic operations like the sum of values, Average and count of rows, etc. by specifying the criterion on specified columns. Similarly, we can perform all those
2 min read
Count number of lines in a text file in Python Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output:
3 min read
How to count the number of lines in a CSV file in Python? Counting the number of lines in a CSV file in Python means determining how many rows the file contains, including or excluding the header depending on your needs. For example, if your CSV file has 100 data rows plus one header row, the total line count is 101. We will use the following dataset to de
2 min read
How to count the number of pages in a PDF file in Python In this article, we will see how can we count the total number of pages in a PDF file in Python, For this article there is no such prerequisite, we will use PyPDF2 library for this purpose. PyPDF2 is a free and open-source pure-Python PyPDF library capable of performing many tasks like splitting, me
4 min read
How to Find Length of a list in Python The length of a list means the number of elements it contains. In-Built len() function can be used to find the length of an object by passing the object within the parentheses. Here is the Python example to find the length of a list using len().Pythona1 = [10, 50, 30, 40] n = len(a1) print("Size of
2 min read