python 上的 xlsxwriter,将 conditional_format 函数与“3_color_scale”一起使用

xlsxwriter on python, Using conditional_format function with '3_color_scale'

我有一个 pandas DataFrame,我将其写入 excel sheet。然后我想对其进行格式化,以便它显示该 DataFrame 的热图。

我认为解决此问题的最佳方法是使用 worksheet.conditional_format() 函数并将 {'type': '3_color_scale'} 作为我的参数。

但是,我注意到这 仅在包含整数的单元格中着色。它不会给任何有浮点数的东西上色。有谁知道如何解决这个问题?

这是一个代码示例。

writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
df.to_excel(writer, sheet_name=selected_factor, startrow=row_location, startcol=col_location)
worksheet = writer.sheets['Sheet 1 testing']
worksheet.conditional_format('B8:E17',{'type': '3_color_scale'})

我在 Python 2.7 并使用 pandas version 0.15.2

编辑

我明白了为什么它给我带来了麻烦,数字被保存为字符串到传播中 sheet 而不是浮点数。

当我 运行 下面的例子时,我没有看到这个问题。它突出显示整数和浮点数:

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20.5, 30, 40, 50.7, 62, 70]})

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

输出: