Puzzle 13 A 10% Discount

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Multiplying | TOC | A Tale of One City 👉

discount.py

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

​ df = pd.DataFrame([
​ [​'Bugs'​, True, 72.3],
​ [​'Daffy'​, False, 30.7],
​ [​'Tweety'​, True, 23.5],
​ [​'Elmer'​, False, 103.9],
​ ], columns=[​'Customer'​, ​'Member'​, ​'Amount'​])

​ df[df[​'Member'​]][​'Amount'​] *= 0.9
​ ​print​(df)

Guess the Output

IMPORTANT

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

images/hline.png

This code will print a warning and then

​ Customer  Member  Amount
​ 0 Bugs True 72.3
​ 1 Daffy False 30.7
​ 2 Tweety True 23.5
​ 3 Elmer False 103.9</code></pre></td>
images/hline.png

The change is not reflected in df. The reason is that Pandas does a lot of work under the hood to avoid copying data. However, in some cases it can’t, and then you’ll get a copy of the data.

The warning is very helpful; sadly, a lot of developers ignore it.

--

--

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.