gpt4 book ai didi

python - 如何链接 pandas 中样式函数的条件?

转载 作者:行者123 更新时间:2023-12-05 02:49:00 25 4
gpt4 key购买 nike

这就是我想要实现的目标

我确实有一个 Pandas Dataframe - 例如这个:

            0           1           2
0 110.718803 119.821042 -52.593518
1 65.180254 33.518722 -69.893688
2 -135.652788 -64.711718 -241.717819
3 237.781393 -56.865142 15.969767
4 141.585158 138.904568 -115.155063
5 10.030938 -59.274415 73.328127
6 106.937681 -3.604859 44.418938
7 -49.478211 -91.574908 160.340627
8 170.744019 -85.764809 246.141857
9 -94.246832 81.069700 -113.460438

基于 3 个条件,单元格的背景颜色应该不同:
cell <= 0 应该是红色的
>= 100 的单元格应该是蓝色的
所有其他单元格

我就是这么做的

我写了这个函数(基于 Pandas 文档 Pandas styling 中的信息:

def highlight_number(row):
return [
'background-color: red; color: white' if cell <= 0
else 'background-color: green; color: white'
for cell in row
]


df.style.apply(highlight_number)

它适用于两种情况。

这是我的问题

我尝试了不同的方法将第三个条件添加到上面的函数中,但我总是返回错误。
你能给我一个提示如何在列表中添加条件吗?
我没有找到答案。非常感谢。

最佳答案

您可以编写一个普通的 for 循环来代替列表理解。

def highlight_number(row):
arr = []
for cell in row:
if cell <= 0:
arr.append('background-color: red; color: white')
elif cell >= 100:
arr.append('background-color: blue; color: white')
else:
arr.append('background-color: white; color: black')
return arr
df.style.apply(highlight_number)

输出:

enter image description here

关于python - 如何链接 pandas 中样式函数的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64197958/

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