pandas DataFrame Filtering
Learn how to filter data in a pandas DataFrame using various methods.
10 min read
Beginner
pandas DataFrame Filtering
Learn to perform the filtering operation on a pandas DataFrame.
python
# Importing the pandas library as pd
import pandas as pd
# Creating a Python Dictionary
dictionary = {
"Fruit": ["Apple", "Orange", "Mango"],
"Weight": ["1kg", "2kg", "5kg"],
"Price": [300, 150, 800],
}
# Creating a Pandas DataFrame
df = pd.DataFrame(dictionary)
# Printing the DataFrame
print(df)You can call the filter() method from a pandas DataFrame to select a subset of the original dataframe according to the specified index labels.
python
# Selecting Fruit and Weight columns
print(df.filter(items=["Fruit", "Weight"]))python
# Selecting specific columns
print(df[["Fruit", "Weight"]])Selecting rows using conditional statements,
python
# Specifying a conditional statement
print(df["Price"] == 300)
# Selecting rows that satisfy a conditional statement
print(df[df["Price"] == 300])python
# Selecting rows that satisfy multiple conditional statements
print(df[(df["Price"] == 300) | (df["Price"] < 300)])You can also select specific rows using the isin() method,
python
print(df['Fruit'].isin(['Apple', 'Orange']))
print(df[df['Fruit'].isin(['Apple', 'Mango'])])