0

I have a situation where I loaded this csv file into pandas DataFrame and sum the values in some of the columns.

The resulting sum was rounded to 3 decimal place for most of the columns except one column (named: Rise). How do I round/approximate the sum (which is a float number) to 3 decimal places?

level-book

I tried the methods listed below in code snippet, the closest rounded the sum to: 0.90200000000000002 instead of 0.902

Here is what I have tried in Jupyter note:-

import numpy as np
import pandas as pd

level_table = pd.read_csv("Level_Book.csv")
level_table.round(3)


BS = level_table["Back Sight"].sum()
FS = level_table["Fore Sight"].sum()
Rise = level_table["Rise"].sum()
Fall = level_table["Fall"].sum()

# I tried the below methods, the closest rounded the sum to: 0.90200000000000002 instead of 0.902
# Rise = np.around(Rise, decimals=3)
# Rise = np.ceil(Rise)
# Rise = np.round(Rise, decimals=3)
# Rise = Rise.apply(np.round())

BS, FS, Rise, Fall

Output = (4.127, 4.127, 0.90200000000000002, 0.902) or (4.127, 4.127, 0.9019999999999999, 0.902)

Expected Output = (4.127, 4.127, 0.902, 0.902)

enter image description here

Umar Yusuf
  • 926
  • 2
  • 13
  • 30

2 Answers2

4

You can do this simply by using apply function:

sleepstudy['Reaction'] =d['Column'].apply(lambda x: round(x, 3))
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
P.Sharma
  • 53
  • 4
-1

This was solved by user2285236 in a comment to the question.

Use the built-in round function:

round(var_Name, value)
  • var_Name is variable you want to round up and
  • value is an integer value of decimal places to which you want to round

Example:

>>> sum = 6.77765345098888
>>> round(sum, 3)
>>> sum
6.777
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Kshitij
  • 14
  • 3