gpt4 book ai didi

python - 更改 pandas.DataFrame 的样式 : Permanently?

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:15 25 4
gpt4 key购买 nike

当我更改 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))

应用于数据框的样式不是永久的。

为了让它们粘在一起,我可以将 (portfolio_df ... 部分的输出分配给同一个数据帧,如下所示:

portfolio_df = (portfolio_df ...

在 Jupyter Notebook 中显示这个覆盖的 portfolio_df,我可以看到样式精美的 DataFrame。但是尝试从模块导入的函数内更改样式,我失败了。我在函数中构造 DataFrame,更改样式,从函数返回(现在)样式化的 DataFrame,将其显示在 Jupyter Notebook 中,我看到一个非样式化的 DataFrame。

编辑

检查样式操作的返回值的类型

s = (portfolio_df.style.apply(...

我看到这个:

>>> type(s)
pandas.io.formats.style.Styler

因此该操作不会返回 DataFrame,而是返回 ...Styler 对象。我错误地认为我可以将这个返回值重新分配给我原来的 DataFrame,从而覆盖它并使样式更改永久化。

问题

将样式应用于 DataFrame 的操作是破坏性操作还是非破坏性操作?答案似乎是风格不会永久改变。现在,我怎样才能让它永久改变?

编辑2

查看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.

因此,在 Jupyter 笔记本中,Styler 有一种方法可以根据应用的样式自动渲染数据帧。

否则(在 iPython 中)它会创建 HTML。

将应用样式的返回值分配给变量

s = (portfolio_df.style.apply(...

我可以在 Jupyter 笔记本中使用它来渲染新样式。

我的理解是:我无法将数据帧输出到 Jupyter 笔记本中并期望它呈现新样式。但我可以输出 s 来显示新样式。

<小时/>

[1]

中的 Styler 类

pandas/pandas/io/formats/style.py

文档字符串,第 39 行。

最佳答案

我可以给你两个建议:

1。编写一个简单的函数来显示数据帧

这是迄今为止最简单、最简单的解决方案。你可以这样写:

def my_style(df:pd.DataFrame, color_columns:list[str]=['roi', 'percent_of_ath']):
return (df
.style
.applymap(lambda v: 'color: red' if v < 0
else None, subset=color_columns)
)

这可以让你编写如下代码:

df.pipe(my_style) # 这将输出格式化的数据帧

或者

from IPython.display import display 

# This will print a nicely formatted dataframe
def my_display(df:pd.DataFrame, style=my_style):
display(df.pipe(style))

2。覆盖 Pandas _repr_html_ 方法

我不建议这样做,但这正是您所要求的;)

from pandas._config import get_option
from pandas.io.formats import format as fmt

def _my_repr_html_(self) -> str | None:
"""
Return a html representation for a particular DataFrame.

Mainly for IPython notebook.
"""
if self._info_repr():
buf = StringIO()
self.info(buf=buf)
# need to escape the <class>, should be the first line.
val = buf.getvalue().replace("<", r"&lt;", 1)
val = val.replace(">", r"&gt;", 1)
return "<pre>" + val + "</pre>"

if get_option("display.notebook_repr_html"):
max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
show_dimensions = get_option("display.show_dimensions")

formatter = fmt.DataFrameFormatter(
self,
columns=None,
col_space=None,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
justify=None,
index_names=True,
header=True,
index=True,
bold_rows=True,
escape=True,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=".",
)
# return fmt.DataFrameRenderer(formatter).to_html(notebook=True)
return self.pipe(my_style).to_html(notebook=True) # <<<< !!! HERE !!!
else:
return None

df.pipe(_my_repr_html_)

pd.DataFrame._repr_html_ = _my_repr_html_

小心!此示例代码不能处理很长或很宽的 DataFrame。

编辑:

上面用于覆盖 repr_html 的代码对 pandas 代码进行了最少的编辑。这是一个最小的工作示例:

def my_style(df:pd.DataFrame, color_columns:list[str]=['roi', 'percent_of_ath']):
return (df.style.applymap(
lambda v: 'color: red' if v < 0 else None, subset=color_columns)
)

def _my_repr_html_(self) -> str | None:
return self.pipe(my_style)._repr_html_() # <<<< !!! HERE !!!

pd.DataFrame._repr_html_ = _my_repr_html_

关于python - 更改 pandas.DataFrame 的样式 : Permanently?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56176720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com