You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas MultiIndex DataFrame使用Styling写入Excel时报错咨询

错误原因

当你使用axis=1对行维度调用style.apply时,每轮传入highlight_max_value_by_condition函数的是1行2列的切片数据,函数需要返回和输入形状完全一致的结果。你原实现中np.nanmax(value) >= condition返回的是单个布尔值,最终输出结果形状为(9,),和预期的(9,2)不匹配,因此触发报错。

修复方案

根据你的实际需求二选一修改highlight_max_value_by_condition函数即可:

方案1:行最大值满足条件时,高亮当前行对应切片的所有单元格

def highlight_max_value_by_condition(value, condition, props=''):
    is_satisfy = np.nanmax(value) >= condition
    # 生成和输入形状一致的数组,所有元素都返回对应样式/空值
    return np.full(value.shape, props if is_satisfy else '')

方案2:仅高亮行中满足>=1条件的最大值单元格

def highlight_max_value_by_condition(value, condition, props=''):
    max_val = np.nanmax(value)
    # 仅匹配同时等于最大值、且最大值满足条件的单元格
    return np.where((value == max_val) & (max_val >= condition), props, '')

修改后重新运行代码即可正常输出带样式的Excel文件。

内容的提问来源于stack exchange,提问作者buggsbunny4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:45:03