0

I am searching for fastest method to get each value in my column with only two digits after dot without using round()

pd.Series:

input:

1.42345
12.33444
111.66777
2.059999

expected output:

1.42
12.33
111.66
2.05

I am thinking to convert it to string and then use slice but in slice i need to use start and stop options, its hard when digits before are in different lenght.

If there will be no other option I will use .str.extract(r'([0-9]{1,5}.[0-9]{2})') , but maybe there is? some limitations to show float without rounding?

its not duplicate topic, solution from this one is rounding values :Truncate to three decimals in Python

sygneto
  • 1,761
  • 1
  • 13
  • 26

3 Answers3

2

One option is to take the floordiv by 0.01 and to divide again the value by 100:

s.floordiv(0.01).div(100)

0      1.42
1     12.33
2    111.66
3      2.05
dtype: float64

It clearly performs better than casting to string and extracting up to the second decimal place:

s = pd.Series(np.random.randn(1_000_000))

%timeit s.astype(str).str.extract(r'(\d+\.\d{2})')
# 1.76 s ± 42.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit s.floordiv(0.01).div(100)
# 42.1 ms ± 3.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit s//0.01/100
# 40.5 ms ± 3.31 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Floor div

s//0.01/100
0      1.42
1     12.33
2    111.66
3      2.05
Name: dol, dtype: float64
BENY
  • 317,841
  • 20
  • 164
  • 234
0

There are new format specifications, String Format Specification Mini-Language:

You can do the same as:

"{0:.2f}".format(1.42345) // output 1.42

Note that the above returns a string. In order to get as float, simply wrap with float(...):

float("{0:.2f}".format(1.42345)) // output 1.42
Rahul Gupta
  • 991
  • 4
  • 12