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

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

正在尝试将此样式器对象转换为 xlsx sheet:

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