1

There are operations to round or floor or ceiling a column/series of a dataframe but how can one specify the precision for a column and truncate the rest of the values?

df = pd.DataFrame({"a": (1.21233123, 1.2412304498), 'b':(2.11296876, 2.09870989)})

Given this simple data frame, lets say I want to truncate column a and column b to 3 precision without rounding, I simply want to remove the rest of the precision.

 df = pd.DataFrame({"a": (1.212, 1.241), 'b':(2.112, 2.098)})

This would be a result df, there should be a column operation that can be executed but it seems that you can only specify precision for rounding.

rye_bread
  • 95
  • 1
  • 3
  • 11

2 Answers2

3

Use numpy.trunc with a bit of trick:

import numpy as np

n_precision = 3
df = np.trunc(df * (10 ** n_precision))/ (10 ** n_precision)
print(df)

       a      b
0  1.212  2.112
1  1.241  2.098

Since np.trunc discards the fractional part, you first multiply numbers by the order of your precision, do np.trunc, divide them back to get the desired output.

Chris
  • 29,127
  • 3
  • 28
  • 51
  • 1
    Interesting, this is a similar approach to @AndyHayden in that there is not a direct function to do this, it has to be contrived from other existing functions even within the trunc function of NumPy. Thanks for the tip! – rye_bread Feb 28 '19 at 07:12
1

You can use round:

In [11]: df.round(3)
Out[11]:
       a      b
0  1.212  2.113
1  1.241  2.099

To "round down" you can subtract 0.001 / 2 from the DataFrame first:

In [12]: (df - 0.0005).round(3)
Out[12]:
       a      b
0  1.212  2.112
1  1.241  2.098
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • 1
    Referencing the example output I had, round does not work, I do not want to round up I simply want to truncate the value at a specified precision for the whole series. – rye_bread Feb 28 '19 at 06:42
  • I am not sure if I understand how that is equivalent because the resulting data frame is completely different? The resulting df has a value of 1.599 at b1 – rye_bread Feb 28 '19 at 06:52
  • yes sure that works but that should not be the solution to truncating, it doesn't seem to be reproducible on different values of a series. For example if there was any number that would change the value before the decimal when 0.0005 was subtracted, the round would be wrong. – rye_bread Feb 28 '19 at 06:55
  • " it doesn't seem to be reproducible on different values of a series." please provide an example. – Andy Hayden Feb 28 '19 at 06:56
  • My mistake, that does cover any case I can think of at the moment. Thanks! – rye_bread Feb 28 '19 at 07:01
  • @rye_bread I agree that it feels like this ought to be easier, e.g. a flag for `round`. – Andy Hayden Feb 28 '19 at 07:03
  • I was looking for someone to just tell me that there was some sort of round function with a parameter but sadly as far as I have found that is not the case. Appreciate the hack though! – rye_bread Feb 28 '19 at 07:05