【问题标题】:Problem with different indexing in pandas and xlsxwriterpandas 和 xlsxwriter 中不同索引的问题
【发布时间】:2020-03-13 13:35:38
【问题描述】:

下面是运行良好的代码:

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

这将创建以下输出。

我的问题是,是否可以在 pandas 索引中包含 Header Data?我想从第一行开始索引。所以标题Data 应该有索引0。这很有用,因为在xlsxwriter 第一行有索引0。

【问题讨论】:

    标签: python python-3.x pandas indexing xlsxwriter


    【解决方案1】:

    首先 index 是一个对象,默认索引从 0 开始。你可以通过输入 swift 它:

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

    输出:

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 2017-04-16
      • 2016-02-17
      • 2018-07-13
      • 2017-02-16
      相关资源
      最近更新 更多