Get Started

Boolean operators with NumPy

Before, the operational operators like < and >= worked with NumPy arrays out of the box. Unfortunately, this is not true for the boolean operators and, or, and not.

To use these operators with NumPy, you will need np.logical_and(), np.logical_or() and np.logical_not(). Here's an example on the my_house and your_house arrays from before to give you an idea:

np.logical_and(my_house > 13, 
               your_house < 15)

This is a part of the course

“Intermediate Python”

View Course

Exercise instructions

  • Generate boolean arrays that answer the following questions:
  • Which areas in my_house are greater than 18.5 or smaller than 10?
  • Which areas are smaller than 11 in both my_house and your_house? Make sure to wrap both commands in print() statement, so that you can inspect the output.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Create arrays
import numpy as np
my_house = np.array([18.0, 20.0, 10.75, 9.50])
your_house = np.array([14.0, 24.0, 14.25, 9.0])

# my_house greater than 18.5 or smaller than 10


# Both my_house and your_house smaller than 11

This exercise is part of the course

Intermediate Python

BeginnerSkill Level
4.6+
772 reviews

Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

Boolean logic is the foundation of decision-making in Python programs. Learn about different comparison operators, how to combine them with Boolean operators, and how to use the Boolean outcomes in control structures. You'll also learn to filter data in pandas DataFrames using logic.

Exercise 1: Comparison OperatorsExercise 2: EqualityExercise 3: Greater and less thanExercise 4: Compare arraysExercise 5: Boolean OperatorsExercise 6: and, or, not (1)Exercise 7: and, or, not (2)Exercise 8: Boolean operators with NumPy
Exercise 9: if, elif, elseExercise 10: WarmupExercise 11: ifExercise 12: Add elseExercise 13: Customize further: elifExercise 14: Filtering pandas DataFramesExercise 15: Driving right (1)Exercise 16: Driving right (2)Exercise 17: Cars per capita (1)Exercise 18: Cars per capita (2)

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free