3.1 C
London
Friday, December 20, 2024
HomePythonOperations in PythonHow to Perform a COUNTIF Function in Python

How to Perform a COUNTIF Function in Python

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Often you may be interested in only counting the number of rows in a pandas DataFrame that meet some criteria.

Fortunately this is easy to do using the following basic syntax:

sum(df.column_name == some_value)

The following examples show how to use this syntax in practice on the following data frame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'x': [3, 4, 5, 6, 7, 8, 9, 10, 10, 12, 13],
                   'y': [3, 4, 5, 7, 9, 13, 15, 19, 23, 24, 29]})

#view head of DataFrame
df.head()

x	y
0	3	3
1	4	4
2	5	5
3	6	7
4	7	9

Example 1: Count Rows Equal to Some Value

The following code shows how to count the number of rows where the x variable is equal to 10:

sum(df.x == 10)

2

The following code shows how to count the number of rows where the x variable is equal to 10 or the y variable is equal to 5:

sum((df.x == 10) | (df.y == 5))

3

The following code shows how to count the number of rows where the x variable is not equal to 10:

sum(df.x != 10)

9

Example 2: Count Rows Greater or Equal to Some Value

The following code shows how to count the number of rows where x is greater than 10:

sum(df.x > 10) 

2

The following code shows how to count the number of rows where x is less than or equal to 7:

sum(df.x 7)
 
5

Example 3: Count Rows Between Two Values

The following code shows how to count the number of rows where x is between 10 and 20:

sum((df.x >= 5) & (df.x 10))

7

Additional Resources

Pandas: How to Find the Difference Between Two Rows
Pandas: How to Drop Rows that Contain a Specific String
Pandas: How to Drop Duplicate Rows in a DataFrame

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories