【问题标题】:Pandas applymap function does not format numbersPandas applymap函数不格式化数字
【发布时间】:2019-09-20 23:39:30
【问题描述】:

我在代码实验室内运行此程序,将字符串格式化为 2 个小数点。但是,它不起作用。请问有什么问题吗?我在 Colab。

当我发出以下命令时:

format = lambda x: '%.2f' % x
frame.applymap(format)  # applies to every single entry

我明白了

            b          d            e
Utah    0.950857    -0.472254   -0.109456
Ohio    -0.738897   0.218620    -0.982334
Texas   0.400049    0.412557    -0.262711
Oregon  1.130821    0.236745    1.921072

但是,当我发布时

frame['e'].map(format)

它返回正确的结果。

Utah       0.27
Ohio       1.61
Texas      0.26
Oregon    -0.74
Name: e, dtype: object

这是我的处决。

【问题讨论】:

  • 这适用于我的电脑...frame=frame.applymap(format)?
  • 我这边不行!请看截图

标签: pandas format-string


【解决方案1】:

它们是您指出的字符串吗?如果没有,您始终可以在 pandas df 上使用 frame.round(2)

如果它是一个字符串,您可以尝试先将列转换为浮点数,然后再应用舍入函数。

for col in frame.columns:
    frame[col] = frame[col].astype(float)
frame = frame.round(2)

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2018-12-18
    • 1970-01-01
    • 2021-08-10
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多