How to Create a Dataframe Using Where Condition in Python

To create a dataframe using a where condition in Python, you can use the where condition on an existing dataframe.

The following example shows how to create a dataframe using a where condition in Python.

Using Where Condition

You can use logical operators to apply a where condition on a dataframe:

# Import pandas library
import pandas as pd

# Create dataframe
df = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
})

# Apply condition
condition = df['Price'] >= 350

# Create new dataframe
new_df = df[condition]

# Show new dataframe
print(new_df)

Output: 👇️

         Date Product_Code Product_Name  Price  Status
0  01-03-2023        A-101       Laptop   4500       1
1  01-03-2023        A-102       Mobile    550       1
4  02-03-2023        B-102      Scanner    350       1

In this example, we use a logical condition to filter the dataframe df and create a new dataframe new_df.

The output shows the new dataframe created from the existing dataframe by applying the condition.

Conclusion

We can use logical operators to apply a where condition on a dataframe in Python.