首页 > 解决方案 > 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。

标签: pythonpython-3.xpandasindexingxlsxwriter

解决方案


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

输出:

在此处输入图像描述


推荐阅读