英文:
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('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)
which gives
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论