截断 pandas df 中值的小数位

Truncate decimal places of values within a pandas df

我可以 truncate 使用 math 中的 truncate 函数单独浮动。但是当试图将相同的函数传递给 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)

尝试将 df['X'] = math.trunc(1000 * df['X']) / 1000; 更改为 df['X'] =[math.trunc(1000 * val) / 1000 for val in df['X']]。希望对你有帮助

我认为最简单的方法是使用 .astype(int) 在您的示例中,它将是:

df[x] = ((df[x]*1000).astype(int).astype(float))/1000