截断 pandas df 中值的小数位

问题描述 投票:0回答:5

我可以使用

truncate
中的
truncate
函数来
math
单独浮动。但是当尝试将相同的函数传递给
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
python pandas math truncate
5个回答
10
投票

您可以使用

applymap

trunc = lambda x: math.trunc(1000 * x) / 1000;

df.applymap(trunc)

6
投票

我相信实现这一目标的最简单方法是使用

.astype(int)
在您的示例中,它将是:

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

2
投票

尝试将

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


2
投票

一个简单的方法是将其转换为整数值,如下所示:

df['X'] = df['X'].astype(int)

0
投票

您可以使用楼层划分。但是,数据类型仍然是浮点数。

import pandas as pd

df = pd.DataFrame([[10.5,10.9,10.1], [10.5,10.9,10.1]])

      0     1
0  10.5  10.1
1  10.5  10.9
    

df = df.floordiv(1)


      0     1
0  10.0  10.0
1  10.0  10.0
© www.soinside.com 2019 - 2024. All rights reserved.