Rajaram K
Rajaram K

Reputation: 13

pandas series sum shows extra precision

I am trying to sum a simple pandas series, and i am getting extraneous results ( by way of extra precision).

Here is the scenario:

import pandas as pd
prices = [2.99, 4.45, 1.36] 
s = pd.Series(prices)
s.sum()

shows the output:

8.8000000000000007

I have tried this:

pd.set_option('display.precision',2)  # No use - still the same result

as well as this:

np.set_printoptions(precision=2)  # no use

pd.show_versions()

gives this output:

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.6.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 61 Stepping 4, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.23.1
pytest: 3.0.5
pip: 9.0.1
setuptools: 39.1.0
Cython: 0.25.2
numpy: 1.13.3
scipy: 0.19.1
pyarrow: None
xarray: None
IPython: 5.1.0
sphinx: 1.5.1
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2016.10
blosc: None
bottleneck: 1.2.1
tables: 3.4.3
numexpr: 2.6.2
feather: None
matplotlib: 2.2.2
openpyxl: 2.4.1
xlrd: 1.0.0
xlwt: 1.2.0
xlsxwriter: 0.9.6
lxml: 3.7.2
bs4: 4.5.3
html5lib: 0.9999999
sqlalchemy: 1.1.5
pymysql: None
psycopg2: None
jinja2: 2.9.4
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 0.6.0

Can anyone help me understand how the result came to be 8.8000000000000007 and how do I display only two decimal digits.

I have tried this aswell - no use:

round(s.sum(),2)

Upvotes: 0

Views: 2220

Answers (1)

jar
jar

Reputation: 2908

If you are okay working with DataFrame then this can be easily achieved with-

import pandas as pd
prices = [2.99, 4.45, 1.36] 
s = pd.DataFrame(prices)
with pd.option_context('display.precision', 2):
    print(s.sum())

Will output-

8.81

EDIT: Or if you insist on using Series, then you could finally use the numpy function around as follows -

>>> import numpy as np
>>> np.around(s.sum(), 2)
0    8.81

Upvotes: 1

Related Questions