How to filter a pandas dataframe based on value counts?

Given a Pandas DataFrame, we have to filter it based on value counts.
Submitted by Pranit Sharma, on August 07, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Filtering is a process of selecting some sort of information according to our specific demands. Filtering pandas is important for learning about the properties of specific elements and hence results in effective data analysis.

Here, we are going to learn how to filter pandas DataFrame based on value counts? When we filter a DataFrame by one column, we simply compare that column values against a specific condition but when it comes to filtering of DataFrame by on value counts, we use value_count which will return the count of total occurrences of each value.

Let us understand with the help of an example,

Python code to filter a pandas dataframe based on value counts

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Mahindra Sales of quarter':[1000,1000,2102,2110],
    'Suzuki Sales of quarter':[1000,1900,2011,2022],
    'Hyundai Sales of quarter':[2000,2000,1000,2230]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("DataFrame1:\n",df,"\n")

# Filtering DataFrame
result = df[df['Mahindra Sales of quarter'].map(df['Mahindra Sales of quarter'].value_counts()) > 1]

# Display result
print("Result:\n",result)

Output:

Example: filter a pandas dataframe based on value counts

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.