Puzzle 9 A Hefty Bonus

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Once Upon a Time | TOC | Free Range 👉

grades.py

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

​ grades = pd.Series([61, 82, 57])
​ bonuses = pd.Series([10, 5, 10, 10])
​ out = grades + bonuses
​ ​print​(out)

Guess the Output

IMPORTANT

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

images/hline.png

This code will print:

​ 0    71.0
​ 1 87.0
​ 2 67.0
​ 3 NaN
​ dtype: float64</code></pre></td>
images/hline.png

pandas.Series and numpy.ndarray are different from Python lists. The + operator on Python lists does concatenation:

​ In [1]: [1, 2, 3] + [4, 5]
​ Out[1]: [1, 2, 3, 4, 5]

numpy.ndarray, and pandas.Series that is built on it, has a different behavior. They will do element-wise operations and will try to match the dimensions as much as possible (known as broadcasting).

​ In [2]: np.array([1,2,3]) + np.array([4,5,6])
​ Out[2]: array([5, 7, 9])
​ In [3]: np.array([1,2,3]) + 3
​…

--

--

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.