Puzzle 9 A Hefty Bonus
Pandas Brain Teasers — by Miki Tebeka (17 / 34)
Published in
2 min readMar 23, 2022
👈 Once Upon a Time | TOC | Free Range 👉
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.
This code will print:
0 71.0
1 87.0
2 67.0
3 NaN
dtype: float64</code></pre></td>
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
…