python-3.xpandasnumpy

how to round numbers after decimal point in python


I am using numpy round function its working well all aspects but when there is 15.65 it should give 15.7 but its giving 15.6. is there any other method to do this ? because i read many threads numpy have this issue.

df1['result']=df1['a'].apply(lambda x: np.round(x, decimals=1))

Solution

  • There's a trick that adds a very small amount to the data and round. But you need to assure that the delta is smaller than your resolution.

    df = pd.Series(np.arange(0,100,0.05))
    
    df.round(1).head()    
    # 0    0.0
    # 1    0.0
    # 2    0.1
    # 3    0.2
    # 4    0.2
    # dtype: float64
    
    (df+1e-10).round(1).head()    
    # 0    0.0
    # 1    0.1
    # 2    0.1
    # 3    0.2
    # 4    0.2
    # dtype: float64