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

条件语句中Pandas Styled DataFrame无法显示问题求助

问题解决:输入'c'后日历不显示的原因及修复

核心问题

在条件判断块中,仅直接引用calendar变量不会触发Pandas Styler对象的渲染显示。非交互式环境(如普通Python脚本)中,Pandas不会自动展示Styler对象,必须主动调用显示/输出方法。

修复方案

场景1:Jupyter Notebook/IPython环境运行

使用IPython的display函数主动渲染Styler对象:

from IPython.display import display
import pandas as pd
import sys
# (你的days、capt、bol、calendar定义代码)

req = input("Please type 'P' if you want to see a picture \nPlease type 'C' if you want to see a month's calendar\nInput:")

if req.lower() == 'c': 
    display(calendar)  # 主动触发显示
elif req.lower() == 'p':
    io.imshow(picture)
    plt.show()  # 补充该行确保图片正常显示
else:
    sys.exit("Invalid Input, closing program")

场景2:普通Python脚本运行

可选择输出文本格式日历,或导出为HTML文件打开:

  • 输出文本格式日历:
import pandas as pd
import sys

# (你的days、capt、bol、calendar定义代码)

req = input("Please type 'P' if you want to see a picture \nPlease type 'C' if you want to see a month's calendar\nInput:")

if req.lower() == 'c': 
    print(calendar.to_string())  # 转换为文本格式输出
elif req.lower() == 'p':
    io.imshow(picture)
    plt.show()
else:
    sys.exit("Invalid Input, closing program")
  • 导出为HTML并自动打开:
import pandas as pd
import sys
import webbrowser
import tempfile

# (你的days、capt、bol、calendar定义代码)

req = input("Please type 'P' if you want to see a picture \nPlease type 'C' if you want to see a month's calendar\nInput:")

if req.lower() == 'c': 
    # 生成临时HTML文件并打开
    with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f:
        f.write(calendar.to_html())
    webbrowser.open(f.name)
elif req.lower() == 'p':
    io.imshow(picture)
    plt.show()
else:
    sys.exit("Invalid Input, closing program")

额外优化建议

  1. 输入提示中的'F'应改为'P',与判断逻辑保持一致,避免用户混淆;
  2. 已定义的redd函数未被应用,若需给日期30添加样式,可在创建calendar时补充:
calendar = pd.DataFrame(days).style.hide(axis='index')\
    .set_caption("January 2004")\
    .set_table_styles([capt,bol])\
    .applymap(redd, props='color: red;')  # 应用样式函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:05:23