Puzzle 10 Free Range
Pandas Brain Teasers — by Miki Tebeka (18 / 34)
Published in
3 min readMar 23, 2022
👈 A Hefty Bonus | TOC | Phil? Nah!? 👉
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.
This code will raise a ValueError.
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…