2017-07-27 46 views
1

我有一个熊猫DataFrame,我写入Excel工作表。然后我想格式化它以显示该DataFrame的热图。xlsxwriter on python,使用'3_color_scale'的条件_格式函数

我认为最好的方法是使用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

编辑

我想通了,为什么这是给我的麻烦,这些数字都被保存作为字符串到电子表格而不是浮动。

回答

1

我在运行以下示例时看不到此问题。它强调了整形和浮点:

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

输出:

enter image description here

+0

@jmcnamra我想通了,为什么它不工作对我来说,这个数字在被存储为字符串不漂浮! –

相关问题