python - 根据条件为选定列的行着色
问题描述
我找到了为数据框的行着色的解决方案。但它为所有列着色。我需要的是为数据框的列组着色。在下面的函数中,我希望能够选择要着色的列。
df = pd.DataFrame({'A':[23,25,10], 'B':[7,8,3], 'C':[8,3,1]})
print (df)
A B C
0 23 7 8
1 25 8 3
2 10 3 1
def highlight_col(x):
#copy df to new - original data are not changed
df = x.copy()
#set by condition
mask = df['A'].between(10 , 21 , inclusive=True)
mask2 = df['A'].between(22 , 26 , inclusive=False)
df.loc[mask, :] = 'background-color: yellow'
df.loc[mask2,:] = 'background-color: red'
return df
df.style.apply(highlight_col, axis=None)
# So instead of df.loc[mask, :] I would like to do : df.loc[mask, ['A', 'B']] for example.
# So I can create another mask for C column and so on.
# Hope it is clear that I don't need subset=IndexSlice
dff.style.apply(highlight_col3, subset=pd.IndexSlice[:, ['A', 'B']], axis=None)
# This will not do the job. Because then I can not color C column differently.
解决方案
创建助手DataFrame
并选择列以更改颜色loc
:
def highlight_col(x):
#set by condition
mask = df['A'].between(10 , 21 , inclusive=True)
mask2 = df['A'].between(22 , 26 , inclusive=False)
x = pd.DataFrame('', index=df.index, columns=df.columns)
x.loc[mask, ['A', 'B']] = 'background-color: yellow'
x.loc[mask2,['A', 'B']] = 'background-color: red'
return x
推荐阅读
- regex - 重复模式的正则表达式
- excel - 使用两个下拉菜单从另一张表中收集特定信息
- javascript - 比较javascript中的时间戳
- android - 使用 API 将 OBB 扩展文件上传到 Google Play 草案工件
- python - Seaborn 和 Pandas:使用 python 中的多索引数据制作多个 x 类别条形图
- sql - sql语句在复杂的where语句中更新多行中的多个值
- raspberry-pi3 - 处理时遇到错误:/var/cache/apt/archives/dpkg_1.18.25_armhf.deb
- excel - VBA代码将excel文件保存到csv
- android - 带有drawermenu和fab的BottomNavigationView
- neo4j - 事务在自定义过程中未按预期工作