【问题标题】:Merging rows with pandas将行与熊猫合并
【发布时间】:2020-10-26 20:41:00
【问题描述】:

我正在尝试使用 pandas 在 excel 中制定时间表。我目前将一天中的时间作为 15 分钟时间范围内的索引,并在每个单元格中打印占据这些类的类。我希望能够将所有具有重复类的行合并到一个大单元格中,但不知道如何做到这一点。

时间表看起来像熊猫数据框: pandas dataframe

如何在 Excel 中打印日程: current excel schedule

我希望日程安排在 excel 中的样子: dream excel schedule

有没有办法做到这一点?

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    我确信有更好的方法,但这是我想出的:

    # create excel workbook from Pandas DataFrame
    df.to_excel('output.xlsx', engine='xlsxwriter')
    wb = load_workbook(filename='output.xlsx')
    ws = wb.active
    
    value = ''
    same_values = []  # list to hold values that are the same
    count = 0
    for row in ws.iter_cols(): # iterate over each column
        for cell in row: # iterate over each row in  column
            if count == 0:  # this if block only get's used once in the beginning
                value = cell.value
                count += 1
                same_values.append(cell.coordinate)
            else:
                if cell.value == ws[same_values[0]].value:  # check if cell value is the same as what is in the same_value list
                    if cell.value is None:  # if the cell.value is none skip
                        continue
                    same_values.append(cell.coordinate)  # if the cell value is the same as what is in the same_value list then append the cell coordinate
                else:  # if the cell value is different than what is in the same_value list then merge everything in the same_value list
                    if len(same_values) > 1:
                        print(same_values)
                        ws.merge_cells(f'{same_values[0]}:{same_values[-1]}')  # the same_value list only stores coordinates i.e ['B2', 'B3', 'B4'] so the merge_cells function takes a range of cells. So we are passing the coordinates of the first instance which is the first value (same_values[0]) of the same_value list and the last instance which is the last value (same_values[-1]) of the same_value list.
                    same_values = [cell.coordinate]
                value = cell.value
    
    wb.save('merged_output.xlsx')
    

    【讨论】:

    • 如果我们逐行迭代,这可以用来合并单元格,你的方法帮助我完成了我的任务
    【解决方案2】:

    也许您正在使用 xlsxwriter 将 Pandas 数据框转换为 excel 文件?

    看起来和这篇文章很相似: Merge rows based on value (pandas to excel - xlsxwriter)

    【讨论】:

    • 你是救命稻草
    猜你喜欢
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2022-12-06
    • 2018-05-07
    • 2020-11-23
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多