簡體   English   中英

如何使用 XlsxWriter 將帶有分隔線的 Dataframe 導出到 Excel

[英]How to export a Dataframe to Excel with divider lines using XlsxWriter

我想使用 xlswriter 將我的 df 導出到 excel 但格式取決於特定單元格的值,即我有一個看起來像這樣的 df:

Date Data1 data2
01/01/1979 50.0. 10.0
01/01/1979 50.0. 11.0
02/01/1979 50.0. 11.0
02/01/1979 50.0. 11.0
02/01/1979 50.0. 11.0
03/01/1979 50.0. 11.0
03/01/1979 50.0. 11.0

從這樣的 df 我想要一個看起來像這樣的 excel 文件:

Date Data1 data2
01/01/1979 50.0. 10.0
01/01/1979 50.0. 11.0
————————————————————-
02/01/1979 50.0. 11.0
02/01/1979 50.0. 11.0
02/01/1979 50.0. 11.0
————————————————————-
03/01/1979 50.0. 11.0
03/01/1979 50.0. 11.0
————————————————————-

當日期更改時,這會在所有行中添加一行。

Date更改時,下面的腳本會在每一行中添加一行:

請將delimiter變量更改為您想要的任何分隔符。

delimiter = '-----'

def f(x):
    return x.append(pd.DataFrame(delimiter, columns=df.columns, index=[('')]))

df_updated = df.groupby('Date', sort=False, group_keys=False).apply(f)

Output:

    Date        Data1   data2
0   1979-01-01  50.0.   10
1   1979-01-01  50.0.   11
    -----       -----   -----
2   1979-01-02  50.0.   11
3   1979-01-02  50.0.   11
4   1979-01-02  50.0.   11
    -----       -----   -----
5   1979-01-03  50.0.   11
6   1979-01-03  50.0.   11
    -----       -----   -----

一種方法是通過 XlsxWriter 在 Excel 中使用條件格式。 像這樣的東西:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Date': ['01/01/1979', '01/01/1979', '02/01/1979',
                            '02/01/1979', '02/01/1979', '03/01/1979',
                            '03/01/1979'],
                   'Data1': [50.0] * 7,
                   'Data2': [11.0] * 7})

df = df[['Date', 'Data1', 'Data2']]

# 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=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Make column A wider for clarity.
worksheet.set_column(0, 0, 12)

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Add a format to use in the conditional format.
format1 = workbook.add_format({'bottom': 1})

# Apply a conditional format to the required cell range.
worksheet.conditional_format(1, 0, max_row, max_col -1,
                             {'type':     'formula',
                              'criteria': '=$A2<>$A3',
                              'format':   format1})


# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:

在此處輸入圖像描述

請注意,您可能希望將數據字符串轉換為實際的 DateTime 對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM