Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncating decimal digits numpy array of floats

Tags:

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 its for one float. I don't want to run a loop on the numpy array, it will be quite expensive. Is there any inbuilt method within numpy which can do this easily? I do need output as a float not string.

like image 836
blackbug Avatar asked Feb 03 '17 10:02

blackbug


People also ask

How do you truncate a floating point number in python?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.

How do I truncate numbers in NumPy?

The numpy. trunc() is a mathematical function that returns the truncated value of the elements of array. The trunc of the scalar x is the nearest integer i which, closer to zero than x. This simply means that, the fractional part of the signed number x is discarded by this function.


1 Answers

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]) 
like image 86
Traxidus Wolf Avatar answered Sep 20 '22 14:09

Traxidus Wolf