Search⌘ K
AI Features

Multiplying Values of Pandas Series

Understand the challenges of floating point arithmetic in pandas Series multiplication. Explore why direct comparisons may fail due to precision limits and learn how to use numpy allclose and decimal for accurate comparisons.

Try it yourself

Try executing the code below to see the result.

Python 3.8
import pandas as pd
v = pd.Series([.1, 1., 1.1])
out = v * v
expected = pd.Series([.01, 1., 1.21])
if (out == expected).all():
print('Math rocks!')
else:
print('Please reinstall universe & reboot.')

Explanation

The out == expected command returns a Boolean pandas.Series. The all method returns True if all elements are True.

When we look at out and expected, they seem the same.

In [1]: out
Out[1]:
0 0.01
1 1.00
2 1.21
dtype: float64
In [2]: expected
Out[2]:
0 0.01
1 1.00
2 1.21
dtype: float64

But, when we compare ...