Puzzle 1 Rectified

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Part 1 Pandas Brain Teasers | TOC | In or Out? 👉

relu.py

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


​ ​def​ ​relu​(n):
​ ​if​ n < 0:
​ ​return​ 0
​ ​return​ n


​ arr = pd.Series([-1, 0, 1])
​ ​print​(relu(arr))

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 problematic line is if n < 0:. n is the result of arr < 0, which is a pandas.Series.

​ In [1]: ​import​ ​pandas​ ​as​ ​pd​
​ In [2]: arr = pd.Series([-1, 0, 1])
​ In [3]: arr < 0
​ Out[3]:
​ 0 True
​ 1 False
​ 2 False
​ dtype: bool

Once arr < 0 is computed, you use it in an if statement, which brings us to how Boolean values work in Python.

Every Python object, not just True and False, has a Boolean value. The documentation states the rules:

Everything is True except

  • 0 numbers: 0, 0.0…

--

--

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.