Puzzle 10 Free Range

Pandas Brain Teasers — by Miki Tebeka (18 / 34)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 A Hefty Bonus | TOC | Phil? Nah!? 👉

in_range.py

​ ​import​ ​pandas​ ​as​ ​pd​

​ nums = pd.Series([1, 2, 3, 4, 5, 6])
​ ​print​(nums[(nums > 2) ​and​ (nums < 5)])

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will raise a ValueError.

images/hline.png

The result of nums>2 is a series of Boolean values:

​ In [1]: nums>2
​ Out[1]:
​ 0 False
​ 1 False
​ 2 True
​ 3 True
​ 4 True
​ 5 True
​ dtype: bool

We can use this Boolean series to select parts of a series with the same size, including, of course, nums.

​ In [2]: nums[nums>2]
​ Out[2]:
​ 2 3
​ 3 4
​ 4 5
​ 5 6
​ dtype: int64

This is known as Boolean indexing.

In some cases, you’d want to combine two or more of these Boolean series to create a more complex condition. Coming from Python, you’re familiar with the and, or…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.