截断pandas df中值的小数位 [英] Truncate decimal places of values within a pandas df
本文介绍了截断pandas df中值的小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用 math
中的 truncate
函数来截断
单个浮点数.但是,当尝试将相同的函数传递给 pandas
df
列时,出现错误.
I can truncate
individual floats using the truncate
function in math
. But when trying to pass the same function to a pandas
df
column I'm getting an error.
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
推荐答案
You can use applymap
trunc = lambda x: math.trunc(1000 * x) / 1000;
df.applymap(trunc)
这篇关于截断pandas df中值的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文