gpt4 book ai didi

python - pandas 数据框样式 - 如何单独对每一行进行颜色映射(不是整体在一起)

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

我有一个像这样的数据框(df),使用颜色图进行样式设置:

#create random 30 x 30 frame
df = pd.DataFrame(np.random.randint(0, 100, (5, 20)))

df.style.background_gradient(cmap='RdYlGn_r')

enter image description here

上面的代码为所有数字的数据框着色(5 x 20 单元格 - 较小的数字为绿色,较大的数字为红色)。

如何为单独考虑的每一行(而不是作为一组 5 x 20 单元格)将小到大着色,即作为单独考虑的第 0 行到第 4 行的 1 行 x 20 列。

===

例如上述 df 的以下 2 个示例,使用 apply 突出显示分别按行和列的中位数。如何按照上面的示例为从小到大的数字每行着色。

def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]

display(
HTML("""<p style="background-color:lightblue;color:black;font-weight: bold">
each row - median highlight
</p>""")
)

display(df.head(5).style.apply(highlight_max, axis=1))

display(
HTML("""<p style="background-color:lightblue;color:black;font-weight: bold">
each col - median highlight
</p>""")
)
display(df.head(5).style.apply(highlight_max, axis=0))

enter image description here

最佳答案

默认情况下,应用背景渐变时会单独考虑每一列。

您可以通过比较第 0 列和第 4 列中的“74”来在顶部图像中验证这一点。

要单独处理每一行,请使用 df.style.background_gradient(cmap='RdYlGn_r', axis=1) .

其他信息:

请参阅下面的代码来生成以下显示,该显示可以很好地为背景着色。

  • 整个数据框(axis=None)
  • 查看每列 (axis=0) [默认]
  • 查看每一行 (axis=1)

enter image description here

import pandas as pd
from io import StringIO
from IPython.display import display
from IPython.display import clear_output
from IPython.display import HTML

dfstr = StringIO(u"""
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
85 83 90 78 70 70 65 79 49 28 14 11 4 52 90 19 78 7 10 50
10 10 10 5 0 4 6 5 5 5 4 2 2 2 2 2 2 2 2 2
16 33 81 81 47 68 20 75 92 65 39 26 53 82 1000 57 4 53 45 18
10 10 10 5 0 4 6 5 30 30 30 2 2 2 2 2 2 2 2 2
100 299 399 50 50 50 50 50 50 50 300 200 201 300 200 300 204 200 305 300
""")
df = pd.read_csv(dfstr, sep="\t")

# df = pd.DataFrame(np.random.normal(random.choice([100, 1000]), random.choice([10, 100]), size=(5, 12)))
# df



display(
HTML("""<br /><p style="background-color:lightblue;color:black;font-weight: bold">
whole dataframe (axis=None) - look at whole data frame
</p>""")
)
display(df.style.background_gradient(cmap='RdYlGn_r', axis=None))

display(
HTML("""<br /><p style="background-color:lightblue;color:black;font-weight: bold">
each column (axis=0). all rows. This is the Default.<br />


</p>""")
)
display(df.style.background_gradient(cmap='RdYlGn_r', axis=0)) #default



display(
HTML("""<br /><p style="background-color:lightblue;color:black;font-weight: bold">
each row (axis=1). all columns. <br />

</p>""")
)
display(df.style.background_gradient(cmap='RdYlGn_r', axis=1))

关于python - pandas 数据框样式 - 如何单独对每一行进行颜色映射(不是整体在一起),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356236/

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