如何在Pandas中为每列单独设置background gradient(基于列自身vmin/vmax)
实现Pandas每列独立的背景渐变效果
我使用Python 3.10.13版本和pandas 2.1.4版本,参考了Pandas表格可视化指南,原示例代码为:
import pandas as pd import numpy as np def make_pretty(styler): styler.set_caption("Weather Conditions") styler.format_index(lambda v: v.strftime("%A")) styler.background_gradient(axis=None, vmin=1, vmax=5, cmap="YlGnBu") return styler weather_df = pd.DataFrame(np.random.rand(10,2)*5, index=pd.date_range(start="2021-01-01", periods=10), columns=["Tokyo", "Beijing"]) weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
原示例的背景渐变是基于整个数据框的全局vmin/vmax,我希望每列单独应用背景渐变,即每列的vmin和vmax对应自身列的数值范围,尝试使用styler.background_gradient(axis='columns', cmap="YlGnBu")但未生效,请问如何实现?
解决方法
问题出在axis参数的取值:pandas的background_gradient方法中,axis=0表示按列独立计算渐变的数值范围(每列用自己的最小/最大值),axis=1表示按行计算,而axis='columns'并不是有效的参数值,所以之前的代码无效。
修改make_pretty函数中的background_gradient调用,将axis设为0,并移除手动指定的vmin和vmax(这样会自动使用每列的最小/最大值作为渐变范围):
import pandas as pd import numpy as np def make_pretty(styler): styler.set_caption("Weather Conditions") styler.format_index(lambda v: v.strftime("%A")) # 按列独立计算背景渐变 styler.background_gradient(axis=0, cmap="YlGnBu") return styler weather_df = pd.DataFrame(np.random.rand(10,2)*5, index=pd.date_range(start="2021-01-01", periods=10), columns=["Tokyo", "Beijing"]) weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty)
扩展说明
如果需要为每列手动指定不同的vmin/vmax,可以通过循环遍历列,结合subset参数单独设置:
def make_pretty(styler): styler.set_caption("Weather Conditions") styler.format_index(lambda v: v.strftime("%A")) # 为每列手动指定vmin/vmax styler.background_gradient(subset=["Tokyo"], axis=0, vmin=0, vmax=5, cmap="YlGnBu") styler.background_gradient(subset=["Beijing"], axis=0, vmin=1, vmax=4, cmap="YlGnBu") return styler
内容的提问来源于stack exchange,提问作者Zhubarb
相关产品推荐
相关产品推荐

