V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
youthfire
V2EX  ›  Python

求教 Pandas 中,怎么控制 DataFrame 中浮点数精度的同时保留末尾的 0?

  •  
  •   youthfire · 2017-12-28 17:55:58 +08:00 · 12082 次点击
    这是一个创建于 2282 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我的期望是,对于某列价格,既保留 2 位小数,都同时能显示出末尾的 0。

    对于序列,控制具体数的 X = decimal.Decimal('%.2f' % X),显然不能起作用
    网上查到的 pd.options.display.float_format = '${:,.2f}'.format,似乎没有任何作用。

    DataFrame 中相关 series 目前就是保留 2 位小数,但浮点数都没有 0
    意思是 2.00 显示为 2,1.90 ,显示为 1.9。
    我希望所有浮点数列为 2.00 ,1.90 ,这样整齐的一列。求教正确语法。
    2 条回复    2017-12-29 02:11:34 +08:00
    youthfire
        1
    youthfire  
    OP
       2017-12-28 21:24:00 +08:00   ❤️ 1
    找到变相解决的方法。

    https://pypi.python.org/pypi/tabulate

    利用 tabulate 的 floatfmt 参数完美解决,比 pandas 自带的控制输出能力强太多,还解决了 print 输出时不整齐的问题
    ryd994
        2
    ryd994  
       2017-12-29 02:11:34 +08:00 via Android   ❤️ 1
    %0.2f
    c printf 语法
    其次,对于价格,最好不要使用浮点数,直接使用整数到分。浮点数的运算取整不知道什么时候会坑
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3088 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:31 · PVG 22:31 · LAX 07:31 · JFK 10:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.