2 回答
TA贡献1818条经验 获得超3个赞
您可以编写普通的 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)
输出:
TA贡献1893条经验 获得超10个赞
我觉得最简单的方法是使用np.select
它接受条件列表和选择列表(就像 if elif 并且也像 else 一样接受默认值)并修改你的函数并使用它,axis=None
因为我们正在应用于整个数据帧(注意你也可用于subset
列的子集)
def highlight_number(dataframe):
conditions = [dataframe <=0,(dataframe>0) & (dataframe>=100)] #your conditions
choices = ['background-color: red; color: white',
'background-color: blue; color: white']
arr = np.select(conditions,choices,'background-color: white; color: black')
return pd.DataFrame(arr,index=dataframe.index,columns=dataframe.columns)
df.style.apply(highlight_number,axis=None)
添加回答
举报