我可以使用math
中的truncate
函数截断
单个 float 。但是当试图将相同的函数传递给 pandas
df
列时,我遇到了一个错误。
import math
import pandas as pd
X = 1.1236
X = math.trunc(1000 * X) / 1000;
#Output
1.123
但是当使用 pandas
df
时:
d = ({
'X' : [1.1234,1.1235],
})
df = pd.DataFrame(data=d)
df['X'] = math.trunc(1000 * df['X']) / 1000;
错误:
df['X'] = math.trunc(1000 * df['X']) / 1000;
TypeError: type Series doesn't define __trunc__ method
最佳答案
您可以使用 applymap
trunc = lambda x: math.trunc(1000 * x) / 1000;
df.applymap(trunc)
关于python - 截断 pandas df 中值的小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56782394/