如何使用 Pandas DataFrame.style?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40421893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:21:19  来源:igfitidea点击:

How do I use pandas DataFrame.style?

pythonpandas

提问by Sumedh Phadke

I am trying to format my dataframe in HTML using the newly included 'style'in Pandas 0.19. I am trying to replicate the same things using the exact same scripts but I get a Stylerobject.

我正在尝试使用Pandas 0.19 中新包含的“样式”在HTML 中格式化我的数据框。我试图使用完全相同的脚本复制相同的东西,但我得到了一个Styler对象。

>>> df
              Security       Price  Change Percentage  ChgNetValue  LastClose
10     Japan Five-Year   -0.207000          -4.020000    -0.008000  -0.199000
13        U.S. 10-Year   97.406250        5274.434452    95.593850   1.812500
20        U.S. 30-Year   93.156250        3481.253980    90.555031   2.601562
23      U.S. 3M T-Bill    0.355000          -2.068966    -0.007500   0.362500
31      U.S. Five-Year  100.015625        7803.952347    98.750237   1.265625
36  Eurozone Five-Year   -0.423000          -3.171000    -0.013000  -0.410000
43       U.S. Two-Year   99.898438       12271.036276    99.090919  25.875000
44      U.K. Five-Year    0.529000          -3.114000    -0.017000   0.546000    
>>> df.style
    <pandas.formats.style.Styler object at 0x0000000008133F28>
>>> s = df.style.applymap(color_negative_red)
>>> s
    <pandas.formats.style.Styler object at 0x00000000035116A0>

I have the exact same function, color_negative_red, as in the documentation. I am doing this in Eclipse, not IPython.

我具有color_negative_red与文档中完全相同的功能。我在 Eclipse 中执行此操作,而不是 IPython。

What I want is to use to_html()and apply conditional formatting to each number in the dataframe. Is there a better way to do this?

我想要的是对to_html()数据框中的每个数字使用和应用条件格式。有一个更好的方法吗?

回答by TomAugspurger

See the note below Out [2]here. Stylerobjects define a _repr_html_which renders the HTML in the notebook.

请参见下面的注释Out [2]在这里Styler对象定义了_repr_html_在笔记本中呈现 HTML 的a 。

To get the actual HTML string, you call styler.render().

要获取实际的 HTML 字符串,请调用styler.render().