如何在不舍入的情况下将值修剪到点后的两个位置,python [英] How to trim value to two places after dot without rounding, python
问题描述
我正在寻找最快的方法来获取我的列中的每个值,而点后仅两位数字而不使用round()
I am searching for fastest method to get each value in my column with only two digits after dot without using round()
pd.Series:
输入:
1.42345
12.33444
111.66777
2.059999
预期输出:
1.42
12.33
111.66
2.05
我正在考虑将其转换为字符串,然后使用slice
,但是在切片中,我需要使用开始和停止选项,当前面的数字长度不同时,它会比较困难.
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.
如果没有其他选择,我将使用.str.extract(r'([0-9]{1,5}.[0-9]{2})')
,但是也许有吗?显示浮动而不舍入时有一些限制吗?
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?
它不是重复的主题,对此的解决方案是舍入值:截断为三位小数在Python中
its not duplicate topic, solution from this one is rounding values :Truncate to three decimals in Python
推荐答案
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)
这篇关于如何在不舍入的情况下将值修剪到点后的两个位置,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!