python - 单元格颜色excel数据框熊猫
问题描述
我需要你的帮助来处理我的数据框。我想为我的 excel 数据框的某个单元格着色。[![图片][1]][1]
正如您在图像中看到的,我想在值为 0 的一周中的每一天用红色着色,如果值为 1,则用绿色着色。(“LU”,“MA”,“ME”...... )
你可以在这里看到我的部分代码:
但它不起作用,我不知道为什么。我尝试了很多可能性。
你能帮助我吗 ?
多谢
解决方案
您需要使用样式器对象而不是数据框来调用to_excel()
. 像这样的东西:
import pandas as pd
def highlight(val):
if isinstance(val, (int, float)):
color = 'red' if val < 0 else 'green'
return 'color: %s' % color
df_final = pd.DataFrame({'Data': [1, "foo", -1, -5, 5, 6, -5]})
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')
styler = df_final.style.applymap(highlight)
styler.to_excel(writer)
writer.save()
输出:
更新了 highlight() 函数,使其仅适用于数字。对于其他数据类型,您可能需要进一步加强/扩展它。
或者,您可以使用 Excel 条件格式,如下所示:
import pandas as pd
# Create a Pandas dataframe from some data.
df_final = pd.DataFrame({'Data': [1, "Foo", -1, -5, 5, 6, -5]})
# 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_final.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add a format. Light red fill with dark red text.
red_format = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
# Add a format. Green fill with dark green text.
green_format = workbook.add_format({'bg_color': '#C6EFCE',
'font_color': '#006100'})
# Calculate the range to which the conditional format is applied.
(max_row, max_col) = df_final.shape
min_row = 1 # Skip header.
min_col = 1 # Skip index.
max_row = min_row + max_row -1
max_col = min_col + max_col -1
# Apply a conditional format to the cell range.
worksheet.conditional_format(min_row, min_col, max_row, max_col,
{'type': 'cell',
'criteria': '<',
'value': 0,
'format': red_format})
worksheet.conditional_format(min_row, min_col, max_row, max_col,
{'type': 'cell',
'criteria': '>=',
'value': 0,
'format': green_format})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出2:
推荐阅读
- android - 多个片段的基本导航片段
- c - 更改 HP Fortify C 规则优先级
- php - 从没有插件的 URL 中删除父页面?
- javascript - 主题的 localStorage
- javascript - 重新渲染的 HTML 不受 jQuery 功能的影响
- sql-server - 使用数据库部署 ASP.NET MVC Entity Framework Web 应用程序
- c++ - 为什么这个指针值不能转换为整数的规则是什么?
- python - 在Python中以所有可能的方式将两个字符组合在一起,而不需要itertools到一定的长度
- angular - httpClient 出错刷新 Angular 中的 url
- python - mongoengine中的sql查询