条件语句中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")
额外优化建议
- 输入提示中的
'F'应改为'P',与判断逻辑保持一致,避免用户混淆; - 已定义的
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
相关产品推荐
相关产品推荐

