python - Pandas 中的条件颜色格式
问题描述
条件格式中的任务(我猜使用样式)Python,Pandas
有一个有两列的板
第二个表应突出显示条件:
- 如果第一列数字超过第二列,则为绿色;
- 如果第一列编号等于第二列,则为黄色;
- 如果第一列编号小于第二列,则为红色。[
谢谢你的帮助!
解决方案
想法是创建新的 DataFrame,由条件填充样式,使用条件Styler.apply
设置行DataFrame.mask
:
def highlight(x):
c1 = 'background-color: green'
c2 = 'background-color: yellow'
c3 = 'background-color: red'
m1 = x.iloc[:, 0] > x.iloc[:, 1]
m2 = x.iloc[:, 0] == x.iloc[:, 1]
df1 = pd.DataFrame(c3, index=x.index, columns=x.columns)
return df1.mask(m1, c1).mask(m2, c2)
df.style.apply(highlight, axis=None)
编辑:
如果只需要设置一列,请使用numpy.select
:
def highlight(x):
c1 = 'background-color: green'
c2 = 'background-color: yellow'
c3 = 'background-color: red'
c = ''
m1 = x.iloc[:, 0] > x.iloc[:, 1]
m2 = x.iloc[:, 0] == x.iloc[:, 1]
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1.iloc[:, 1] = np.select([m1, m2], [c1, c2], default=c3)
return df1
推荐阅读
- codenameone - 将文本提示保留在 textArea 的底行 - cn1
- google-cloud-platform - 气流调度,重新运行失败的任务
- java - 无法使用 Java 读取具有日期字段的 Excel 单元格值
- python - 使用 Python 访问 Fastmail CalDAV
- asp.net - APP_CODE 目录是否仍在 ASP.NET 应用程序中使用?
- html - Chrome 上的 CSS 模糊过滤器中断
- firefox - 使用 Firefox 调整大小时刷新页面
- date - 从开始和结束日期获取文件的动态路径
- sql - 为什么我得到以下错误 LISTAGG 函数:“字符串连接的结果太长”?*
- java - 计算经过的时间?