Pandas DataFrame样式设置报错:'NoneType'无rstrip属性
DataFrame样式渲染时的AttributeError问题
原始DataFrame
Server Env. Model Percent_Utilized server123 Prod Cisco. 50 server567. Prod Cisco. 80 serverabc. Prod IBM. 100 serverdwc. Prod IBM. 45 servercc. Prod Hitachi. 25 Avg 60 server123Uat Uat Cisco. 40 server567u Uat Cisco. 30 serverabcu Uat IBM. 80 serverdwcu Uat IBM. 45 serverccu Uat Hitachi 15 Avg 42
现有代码及问题
需求是基于Percent_Utilized列给DataFrame应用背景色样式,现有代码如下:
def color(val): if pd.isnull(val): return elif val > 80: background_color = 'red' elif val > 50 and val <= 80: background_color = 'yellow' else: background_color = 'green' return 'background-color: %s' % background_color def color_for_avg_row(row): styles = [''] * len(row) if row['Server'] == 'Avg': if row['Percent_Utilized'] > 80: color = 'background-color: red' elif row['Percent_Utilized'] > 50: color = 'background-color: yellow' else: color = 'background-color: green' styles = [color for _ in row.index] return pd.Series(styles, index=row.index) df_new = (df.style .apply(color_for_avg_row, axis=1) .applymap(color, subset=["Percent_Utilized"])) df_new
运行时触发错误:
AttributeError: 'NoneType' object has no attribute 'rstrip'
问题原因及解决方法
错误根源是color函数遇到空值时返回None,而Pandas的Styler组件要求每个单元格的样式返回值必须是字符串类型——即使是无样式,也要返回空字符串'',不能返回None。
修改color函数,将空值分支的返回值改为空字符串:
def color(val): if pd.isnull(val): return '' # 替换原return语句,返回空样式字符串 elif val > 80: background_color = 'red' elif val > 50 and val <= 80: background_color = 'yellow' else: background_color = 'green' return 'background-color: %s' % background_color
修改后,Styler渲染时就能正确处理空值单元格,不会再触发NoneType相关的属性错误。
额外说明:如果Percent_Utilized列的空值是显示层面的合并单元格导致,而非实际NaN值,需要将判断条件调整为val == ''以适配字符串空值场景。
内容的提问来源于stack exchange,提问作者user1471980
相关产品推荐
相关产品推荐

