Pandas: Get values from column that appear more than X times

Learn, how to get values from column that appear more than X times in Python Pandas?
Submitted by Pranit Sharma, on November 30, 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.

Problem statement

Suppose we are given the data frame with multiple columns like id, product, type, and sales. Now suppose we need to get all the values from the column 'product' that appear more than two times.

Getting values from column that appear more than X times

For this purpose, we will first create a data frame after that we will count all the values of the product column and store the result in a list, and finally, we will filter the values of this column by applying a condition.

Let us understand with the help of an example,

Python program to get values from column that appear more than X times

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({
    'id':[1,2,3,4,5,6],
    'product':['tv','tv','tv','fridge','car','bed'],
    'type':['A','B','C','D','E','F'],
    'sales':[10000,20000,21323,78264,82542,487613]
})

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

# Getting count of produt column values
count = df.product.value_counts()

# Display count
print("Count:\n",count,"\n")

# Filtering product values if more than 2
res = count[count>2].index[0]

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

Output

The output of the above program is:

Example: Get values from column that appear more than X times

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.