Openpyxl - 合并 pandas 列中的相同单元格

问题描述 投票:0回答:1

我正在尝试使用 openpyxl 将 Pandas 数据框输出到 Excel 文件中:
我想使用 openpyxl 将数据帧的每个 ID 的多行合并到单个单元格中。

我分别在 pandas 中有以下列和数据框列表

dict1 = {'ID': ['6610', '6610', '6610', '6620', '6620', '7540', '7540'],
 'NEW_ID': ['6615', '6615', '6615', '   ', '   ', 'nan', 'nan'],
 'OLD_PRICE': [17.22, 17.9, 17.22, 27.49, 20.42, 30.73, 29.55],
 'NEW_PRICE': [17.22, 17.22, 27.49, 18.99, 27.49, 29.55, 27.49],
 'LABEL': ['  NaN1', '  NaN2', '  NaN4', 'nan', '  Na', 'A', 'B']}

df = pd.DataFrame(dict1)

工作簿现在看起来:

之前:

我试图让它最终看起来: 之后:

python python-3.x pandas openpyxl
1个回答
0
投票

如果您使用“set_index”,您可以实现您想要的效果,但具有合并单元格的列必须位于开头,要求 LABEL 列移动到第 3 列。
除非您使用 Xlwings 之类的工具在 Excel 中复制/粘贴,否则将列移回最后一列并非易事。

import pandas as pd
from pandas import ExcelWriter


dict1 = {
 'ID': ['6610', '6610', '6610', '6620', '6620', '7540', '7540'],
 'NEW_ID': ['6615', '6615', '6615', '   ', '   ', 'nan', 'nan'],
 'OLD_PRICE': [17.22, 17.9, 17.22, 27.49, 20.42, 30.73, 29.55],
 'NEW_PRICE': [17.22, 17.22, 27.49, 18.99, 27.49, 29.55, 27.49],
 'LABEL': ['  NaN1', '  NaN1', '  NaN1', ' Na', ' Na', 'A', 'B']
}

excel_file = "filtered_test.xlsx"
df = pd.DataFrame(dict1)
df.insert(2, 'LABEL', df.pop('LABEL'))

df = df.set_index(["ID", "NEW_ID", "LABEL", "OLD_PRICE", "NEW_PRICE"])

with ExcelWriter(excel_file) as writer:
    df.to_excel(writer, startrow=-1)

    worksheet = writer.sheets['Sheet1']
    writer.sheets['Sheet1'].autofit()

© www.soinside.com 2019 - 2024. All rights reserved.