Ugu*_*gur 10 python pandas jupyter-notebook pandas-styles
当我改变 a 的样式时pandas.DataFrame,例如像这样
# color these columns
color_columns = ['roi', 'percent_of_ath']
(portfolio_df
.style
# color negative numbers red
.apply(lambda v: 'color: red' if v < 0 else 'color: black',
subset=color_columns)
# color selected cols light blue
.apply(lambda s: 'background-color: lightblue',
subset=color_columns))
Run Code Online (Sandbox Code Playgroud)
应用于数据框的样式不是永久性的。
为了让它们粘在一起,我可以将部件的输出分配(portfolio_df ...给同一个数据帧,如下所示:
portfolio_df = (portfolio_df ...
Run Code Online (Sandbox Code Playgroud)
portfolio_df在 Jupyter Notebook 中显示覆盖的内容,我可以看到样式精美的 DataFrame。但是尝试从模块导入的函数内更改样式,我失败了。我在函数中构造 DataFrame,更改样式,从函数返回(现在)样式化的 DataFrame,将其显示在 Jupyter Notebook 中,我看到一个非样式化的 DataFrame。
检查样式操作的返回值的类型
s = (portfolio_df.style.apply(...
我看到这个:
>>> type(s)
pandas.io.formats.style.Styler
Run Code Online (Sandbox Code Playgroud)
所以该操作不会返回一个DataFrame,而是一个...Styler对象。我错误地认为我可以将此返回值重新分配给我的原始 DataFrame,从而覆盖它并使样式更改永久化。
将样式应用于 DataFrame 的操作是破坏性操作还是非破坏性操作?答案似乎是风格不会永久改变。现在,我怎样才能让它永久改变呢?
查看 的源代码Pandas,我查看了文档字符串class Styler(参见 [1]):
If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
to automatically render itself. Otherwise call Styler.render to get
the generated HTML.
Run Code Online (Sandbox Code Playgroud)
因此,在 Jupyter 笔记本中,Styler 有一个方法可以自动渲染数据帧,尊重所应用的样式。
否则(在 iPython 中)它会创建 HTML。
将应用样式的返回值分配给变量
s = (portfolio_df.style.apply(...
我可以在 Jupyter 笔记本中使用它来渲染新样式。
我的理解是:我无法将数据帧输出到 Jupyter 笔记本中并期望它呈现新样式。但我可以输出s来显示新的样式。
[1]class Styler在
pandas/pandas/io/formats/style.py
文档字符串,第 39 行。