Skip to main content
 首页 » 编程设计

python之截断 pandas df 中值的小数位

2025年05月04日15cyq1162

我可以使用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)