如何更改一个单元格的颜色,比较数据框中两个单元格的值

huangapple go评论123阅读模式
英文:

How to change the color of one cell, compare values of two cells in DataFrame

问题

我想将'petal_length'的值与'sepal_width'进行比较,如果小于'sepal_width'的值,则将其填充为红色,否则填充为绿色。

英文:

I have a dataset and a function that fills only the values in one column with a color, I want to compare this value with the value from another column. And if it is greater than in the other column, paint the cell in green, if not, then in red, but only in the first column

Here is a dataset and code that draws only the value in one column, and compares it to the static value 5.1

import pandas as pd
import seaborn as sns

iris = sns.load_dataset('iris')
df = iris.sample(n=10, random_state=1)
df

如何更改一个单元格的颜色,比较数据框中两个单元格的值

and function:

def highlight_cells(val):
    color = 'yellow' if val == 5.1 else ''
    return 'background-color: {}'.format(color)

df.style.applymap(highlight_cells, subset=['petal_length'])

如何更改一个单元格的颜色,比较数据框中两个单元格的值

I want to compare the value of 'petal_length' with 'sepal_width' and if it is smaller, fill it in red, if not, fill it in green.

答案1

得分: 2

您可以执行以下操作

```python
import pandas as pd
import seaborn as sns

iris = sns.load_dataset('iris')
df = iris.sample(n=10, random_state=1)

def highlight_cells(row):
    color = 'red' if row['petal_length'] < row['sepal_width'] else 'green'
    return ['background-color: {}'.format(color) if i == 'petal_length' else '' for i in row.index]

df.style.apply(highlight_cells, axis=1)

得到的结果如下图所示:


[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/rBEtz.png
英文:

YOu could do the following:

import pandas as pd
import seaborn as sns

iris = sns.load_dataset(&#39;iris&#39;)
df = iris.sample(n=10, random_state=1)

def highlight_cells(row):
    color = &#39;red&#39; if row[&#39;petal_length&#39;] &lt; row[&#39;sepal_width&#39;] else &#39;green&#39;
    return [&#39;background-color: {}&#39;.format(color) if i == &#39;petal_length&#39; else &#39;&#39; for i in row.index]

df.style.apply(highlight_cells, axis=1)

which gives

如何更改一个单元格的颜色,比较数据框中两个单元格的值

huangapple
  • 本文由 发表于 2023年2月13日 23:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定