[英]How to truncate a series/column of a data frame with single operation
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. 给定这个简单的数据框,可以说我想将a列和b列的精度截断为3而不舍入,我只想删除其余精度。
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. 这将是df的结果,应该有可以执行的列操作,但似乎您只能指定舍入精度。
Use numpy.trunc
with a bit of trick: 使用
numpy.trunc
有一些技巧:
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. 由于
np.trunc
丢弃小数部分,因此您首先将数字乘以精度的顺序,然后执行np.trunc
,将它们除以得到所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.