【问题标题】:Truncate decimal places of values within a pandas df截断熊猫df中值的小数位
【发布时间】:2019-06-27 00:12:23
【问题描述】:

我可以使用math 中的truncate 函数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

【问题讨论】:

  • 为什么要使用 truncate 而不是 df.round?
  • 与其他具有 n 个小数位的数字进行比较。 11.23亿和11.24亿相差很大

标签: python pandas math truncate


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以使用applymap

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

    【讨论】:

    • 不错的答案@Anthony Kong
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2018-09-25
      • 1970-01-01
      • 2018-07-14
      • 2015-04-30
      • 1970-01-01
      相关资源
      最近更新 更多