python - pandas 和 xlsxwriter 中不同索引的问题
问题描述
这是工作正常的代码:
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(1,1,1,1, {'type': '3_color_scale'}) ##CHANGES THE COLOR OF SECOND ROW
# Close the Pandas Excel writer and output the Excel file.
writer.save()
这将创建以下输出。
我的问题是,是否可以将 Header 包含Data
在 pandas 索引中?我想从第一行开始索引。所以 HeaderData
应该有索引 0。它很有用,因为在xlsxwriter
第一行有索引 0。
解决方案
首先 index 是一个对象,默认索引从 0 开始。您可以通过键入以下命令快速调用它:
df.index += 1
至于标头的索引名称,pandas 方法 to_excel 采用一个称为 index_label 的参数。所以你的代码应该是:
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
df.index += 1
# 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', index_label='0')
# 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(1,1,1,1, {'type': '3_color_scale'}) ##CHANGES THE COLOR OF SECOND ROW
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
推荐阅读
- angular - 以角度上传文件后刷新表格列表
- r - 使用 CSS 选择器在 R 中进行网页抓取
- r - 如何在分组条形图中使分组条更靠近?
- java - Java JIT编译可以在返回始终相同的值时优化方法吗?
- python - 在 Django 中没有从 timezone.now 获取时间
- webpack - 如何在没有 HTML 的情况下加载带有哈希的 webPack 包?
- javascript - 更改功能内的光滑滑块功能不起作用
- php - 如何从 PHP 7 中的嵌套包含文件中跳出 while 循环?
- asp.net-core - 使用 Angular 6 ag-grid 和 ASP.NET 和 EF Core 2.1 进行服务器端过滤
- android - 在 ListView 中显示特定于 Firebase 的子数组项