2017-11-25 93 views
2

尝试此样式器对象转换为XLSX表:MetaSerialisable对象参数后,**必须是一个映射,不是Unicode

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

enter image description here

但是,我得到的错误:

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() 
+0

做,如果你忽略'to_excel()'一部分,你得到同样的错误? – jmcnamara

+0

@jmcnamara不能,样式器对象工作正常 –

+0

好的。从Pandas [Styler](http://pandas.pydata.org/pandas-docs/stable/style.html)文档看来,'background_gradient'看起来只能在Html输出中被支持。即使如此,只有使用'openpyxl'作为Excel引擎才支持'to_excel()'支持的样式。 – jmcnamara

回答

2

大熊猫斯泰勒使用openpyxl为Excel的引擎时,仅在to_excel()支持。同样来自Pandas docs,它似乎只能在Html输出中支持background_gradient。

作为替代方案,您可以使用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() 

enter image description here

相关问题