Menu
Coddy logo textTech

Multiple Condition Indexing

Lesson 15 of 18 in Coddy's Numpy Fundamentals course.

We learned how to apply conditions, but sometimes we want to apply multiple conditions at the same time.

Python ways to combine different conditions are: and or not

In numpy it is different.

We use:

PythonNumpy
and&
or|
not~

Note: Every condition must be inside the parenthesis (). look at the examples to see what we mean.

Example 1

Retrieve all elements that are bigger than 5 and smaller than 10

ary = np.array([1, 2, 3, 5, 8, 3, 9, 10, 2])
ary[(ary > 5) & (ary < 10)]
>>> [8, 9]

Example 2

Retrieve all elements that are smaller than 3 or bigger than 7

ary = np.array([1, 5, 2, 3, 8, 7])
ary[(ary < 3) | (ary > 7)]
>>> [1, 2, 8]

Example 3

Retrieve all elements that are not equal to 5

ary = np.array([1, 5, 2])
ary[~(ary == 5)]
>>> [1, 2]

 

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a function called condition_master that receives a python list and returns all the elements that are smaller or equal to 0 or bigger than 5 and not equal to 10.

Return the result as a python list

  • To convert a numpy array to a python list use: str(list(ary))

Try it yourself

import numpy as np
def condition_master(lst):
    # Complete here

All lessons in Numpy Fundamentals