-1

I have a pandas DataFrame with decimal values, say as follows:

import pandas as pd
df = pd.DataFrame({'a':[0.001234, 0.003986, 0.12], 'b':['aa', 'bb', 'cc']})

I need to limit the number of decimal digits of 'a' column to 5, without rounding. So the result should be :

result = pd.DataFrame({'a':[0.00123, 0.00398, 0.12], 'b':['aa', 'bb', 'cc']})

(zeros can be added at the end of 0.12, this is not a problem).

How can I do this? I have tried

df['a'] = df['a'].round(decimals=5)

but of course, as expected, it does not do the trick.

Thanks in advance,

M

Matina G
  • 1,452
  • 2
  • 14
  • 28
  • 1
    @yatu Also [Pandas Dataframe How to cut off float decimal points without rounding?](https://stackoverflow.com/questions/56780561/pandas-dataframe-how-to-cut-off-float-decimal-points-without-rounding) – pault Oct 28 '19 at 16:56
  • Adapting from the dupe `df.a.floordiv(1e-5).div(1e5)` – yatu Oct 28 '19 at 16:57
  • floor division by 10**(-5) then division by 10**5 does the trick. Float formatting doesn't, it rounds values. – Matina G Oct 28 '19 at 17:15

1 Answers1

1

How about:

df['a'] = (df['a'] * 1e5).astype(int) / 1e5

Equivalently:

df['a'] = (df['a'] // 1e-5) * 1e-5

Output:

         a   b
0  0.00123  aa
1  0.00398  bb
2  0.12000  cc
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74