Truncating decimal digits numpy array of floats

后端 未结 2 1609
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 02:22

I want to truncate the float values within the numpy array, for .e.g.

2.34341232 --> 2.34 

I read the post truncate floating point but i

相关标签:
2条回答
  • 2020-12-11 03:00

    Try out this modified version of numpy.trunc().

    import numpy as np
    def trunc(values, decs=0):
        return np.trunc(values*10**decs)/(10**decs)
    

    Sadly, numpy.trunc function doesn't allow decimal truncation. Luckily, multiplying the argument and dividing it's result by a power of ten give the expected results.

    vec = np.array([-4.79, -0.38, -0.001, 0.011, 0.4444, 2.34341232, 6.999])
    
    trunc(vec, decs=2)
    

    which returns:

    >>> array([-4.79, -0.38, -0.  ,  0.01,  0.44,  2.34,  6.99])
    
    0 讨论(0)
  • 2020-12-11 03:01

    Use numpy.round:

    import numpy as np
    a = np.arange(4) ** np.pi
    a
    => array([  0.        ,   1.        ,   8.82497783,  31.5442807 ])
    a.round(decimals=2)
    => array([  0.  ,   1.  ,   8.82,  31.54])
    
    0 讨论(0)
提交回复
热议问题