How to Create Boolean Series From Dataframe in Python

To create a boolean series from a dataframe in Python, you can apply a condition to the dataframe and then use the squeeze() function to convert the result into a series.

Method: Apply Condition & squeeze() Function

df['column_name'].gt(value).squeeze()

The following example shows how to create a boolean series from a dataframe in Python by applying a condition and using the squeeze() function.

Applying Condition & squeeze() Function

We can apply a condition and use the squeeze() function to create a boolean series.

Let’s see how to apply a condition and use the squeeze() function in Python:

# Import pandas library
import pandas as pd

# Create the DataFrame
office_stuff = 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]
})

# Create a boolean series 
bool_ser = office_stuff['Price'].gt(300).squeeze() 

# Print the boolean series
print(bool_ser)

Output: 👇️

0     True
1     True
2    False
3    False
4     True
5    False
Name: Price, dtype: bool

In this example, we use the gt method to check if the values in the Price column are greater than 300 and then use the squeeze() function to convert the result into a boolean series bool_ser.

The output shows the boolean series created from the dataframe.

Conclusion

We can use the squeeze() function to create a boolean series from a dataframe in Python.