简体   繁体   中英

Openpyxl Merge cells with same value in one column

I have write the dataframe below to an excel file

df = {'name':  ['a', 'b', 'b', 'b', 'c', 'd', 'd', 'e'],
        'type': ['tiger', 'caterpillar', 'butterfly', 'butterfly', 'dolphin', 'tadpole', 'frog', 'dog'],
        'month1_weight': ['33', '0', '0', '0', '59', '3', '0', '0'],
        'month2_weight': ['0', '0', '20', '20', '65', '0', '10', '2'],
        }
dataframe = pd.DataFrame(df)

name      type         month1_weight  month2_weight
a         tiger        33             0
b         caterpillar  0              0
b         butterfly    0              20
b         butterfly    0              20
c         dolphin      59             65
d         tadpole      3              0
d         frog         0              10
e         dog          0              2

在此处输入图像描述

How can I merge the cells in the name column in Excel and make it be like this:

在此处输入图像描述

First add the multilevel index to your dataframe using set_index(["name", "type"]) then using the pandas.ExcelWriter object you can write the required dataframe to the excel sheet. Use:

from pandas import ExcelWriter

dataframe = pd.DataFrame(df).set_index(["name", "type"])    
with ExcelWriter("excel_file.xlsx") as writer:
    dataframe.to_excel(writer)

After executing the above code the contents of your excel_file should look like:

在此处输入图像描述


EDIT (See comments):

Replace:

for col_num, value in enumerate(dataframe.columns.values): 
    worksheet_O.write(0, col_num + 1, value, header_format)

with:

for col_num, value in enumerate(dataframe.reset_index().columns): 
    worksheet_O.write(0, col_num, value, header_format) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM