Skip to main content
 首页 » 编程设计

python之** 之后的 MetaSerialisable 对象参数必须是映射,而不是 unicode

2024年10月01日7bhlsheji

尝试将此样式器对象转换为 xlsx 工作表:

 avg.style.background_gradient(cmap='RdYlGn',low=.09,high=.18,axis=1).to_excel('test.xlsx',engine='xlsxwriter') 

但是,我得到了错误:

 TypeError: MetaSerialisable object argument after ** must be a mapping, not unicode 

当我尝试时:

 avg.style.background_gradient({'cmap':'RdYlGn'},low=.09,high=.18,axis=1).to_excel('test.xlsx',engine='xlsxwriter') 
 
TypeError: ("unhashable type: 'dict'", u'occurred at index (Gain/Expsr%, 5)') 

这里没有背景渐变输出:

writer = pd.ExcelWriter('usher.xlsx') 
df.style.background_gradient(cmap='RdYlGn').to_excel(writer,engine='openpyxl') 
writer.save() 

请您参考如下方法:

当使用 openpyxl 作为 Excel 引擎时,Pandas Styler 仅在 to_excel() 中受支持。同样来自 Pandas docs看起来 background_gradient 可能只在 Html 输出中受支持。

作为替代方案,您可以通过 XlsxWriter and Pandas 在 Excel 中使用条件格式相反。

import pandas as pd 
 
 
# Create a Pandas dataframe from some data. 
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) 
 
# Create a Pandas Excel writer using XlsxWriter as the engine. 
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter') 
 
# Convert the dataframe to an XlsxWriter Excel object. 
df.to_excel(writer, sheet_name='Sheet1') 
 
# Get the xlsxwriter workbook and worksheet objects. 
workbook  = writer.book 
worksheet = writer.sheets['Sheet1'] 
 
# Apply a conditional format to the cell range. 
worksheet.conditional_format('B2:B8', {'type': '3_color_scale'}) 
 
# Close the Pandas Excel writer and output the Excel file. 
writer.save()